반응형
요소의 부모 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를 피하는 것을 선호합니다.
당신은 다음 parentNode을 Element상속합니다 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부모 요소를 가져옵니다.
도움이 될 수 있습니다.
ParentID = pDoc.offsetParent;
alert(ParentID.id);
var parentDiv = pDoc.parentElement
편집 : 때로는 경우 parentNode에 따라입니다.
https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
요소의 부모를 아는 것은 요소의 "실제 흐름"을 배치하려고 할 때 유용합니다.
아래의 코드는 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 -->
참고 URL : https://stackoverflow.com/questions/6856871/getting-the-parent-div-of-element
반응형
'Programming' 카테고리의 다른 글
| 디버깅을 종료 할 때 Visual Studio 2013이 IIS Express 앱을 닫지 못하게하려면 어떻게해야합니까? (0) | 2020.05.15 |
|---|---|
| Firebase 콘솔을 사용하지 않고 Firebase 클라우드 메시징 알림을 보내려면 어떻게해야합니까? (0) | 2020.05.15 |
| Python에서 Pandas와 NumPy + SciPy의 차이점은 무엇입니까? (0) | 2020.05.15 |
| Swift에서 유형이 지정된 배열을 어떻게 확장 할 수 있습니까? (0) | 2020.05.15 |
| postgresql에서 DB에 대한 사용자를 만드는 방법은 무엇입니까? (0) | 2020.05.15 |