[javascript] 요소의 부모 div 어떻게 가져옵니까?

이것은 정말 간단해야하지만 문제가 있습니다. 자식 요소의 부모 div는 어떻게 얻습니까?

내 HTML :

<div id="test">
    <p id="myParagraph">Testing</p>
</div>

내 JavaScript :

var pDoc = document.getElementById("myParagraph");
var parentDiv = ??????????   

생각 document.parent했거나 parent.container효과가 있었지만 계속 not defined오류 가 발생합니다. 의 pDoc정의는 있지만 특정 변수는 아닙니다.

어떤 아이디어?

추신 : 가능하다면 jQuery를 피하는 것을 선호합니다.



답변

당신은 다음 parentNodeElement상속합니다 Node.

parentDiv = pDoc.parentNode;

편리한 참고 자료 :

  • DOM2 Core 사양-모든 주요 브라우저에서 잘 지원
  • DOM2 HTML 사양 -DOM 과 HTML 간의 바인딩
  • DOM3 핵심 사양-일부 주요 브라우저에서 모두 지원되는 것은 아닌 일부 업데이트
  • HTML5 사양 -이제 DOM / HTML 바인딩이 포함되어 있습니다.

답변

직계 부모보다 멀리 떨어진 특정 유형의 요소를 찾고 있다면 DOM을 찾을 때까지 또는 그렇지 않은 DOM을 위로 올리는 함수를 사용할 수 있습니다.

// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el && el.parentNode) {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }

  // Many DOM methods return null if they don't 
  // find the element they are searching for
  // It would be OK to omit the following and just
  // return undefined
  return null;
}

답변

속성 pDoc.parentElement또는 pDoc.parentNode부모 요소를 가져옵니다.


답변

var parentDiv = pDoc.parentElement

편집 : 때로는 경우 parentNode에 따라입니다.

https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement


답변

도움이 될 수 있습니다.

ParentID = pDoc.offsetParent;
alert(ParentID.id); 

답변

요소의 부모를 아는 것은 요소의 “실제 흐름”을 배치하려고 할 때 유용합니다.

아래의 코드는 id가 제공된 element의 parent의 id를 출력합니다. 정렬 불량 진단에 사용할 수 있습니다.

<!-- Patch of code to find parent -->
<p id="demo">Click the button </p>
<button onclick="parentFinder()">Find Parent</button>
<script>
function parentFinder()
{
    var x=document.getElementById("demo");
    var y=document.getElementById("*id of Element you want to know parent of*");
    x.innerHTML=y.parentNode.id;
}
</script>
<!-- Patch ends -->

답변