Reputation: 52540
If I have 2 HTML elements, how can I easily tell if 1 is a child of the other?
var parent = document.getElementById('shapes');
var child = document.getElementById('star');
Is there any kind of function on an element like child.getParentElement()
that I could compare with like child.getParentElement() == parent
?
I understand parent.children
gives me back an array of children, so I suppose I could use a for loop and compare each to child
. Is there an easier single-function way to do this?
No jQuery or other libraries.
Upvotes: 2
Views: 2672
Reputation: 5267
If you need only the direct child from parent element, take a look at below example:
<div id="div1">
Parent
<div id="div2">
Child
<div id="div3-1">
N-child 1
</div>
<div id="div3-2">
N-child 2
</div>
</div>
</div>
<input type="button" id="btn-action" value="Run" />
<div id="result"></div>
JavaScript:
document.getElementById("btn-action").addEventListener("click",function(e) {
var div1 = document.getElementById("div1"),
div2 = document.getElementById("div2"),
nchild1 = document.getElementById("div3-1"),
nchild2 = document.getElementById("div3-2");
document.getElementById("result").innerHTML =
"<br/>div2 is child of div1? - " + fnIsChild(div1, div2) +
"<br/>div3-1 is child of div1? - " + fnIsChild(div1, nchild1) +
"<br/>div3-2 is child of div1? - " + fnIsChild(div1, nchild1);
});
function fnIsChild(parentElem, childElem) {
var childNodes = parentElem.childNodes,
max = childNodes.length,
n;
for(n = 0; n < max; n += 1) {
if(childNodes[n] === childElem) return true;
}
return false;
}
Upvotes: 1
Reputation: 895
You can also use child.parentElement
to get parent.
I also Want to point out you can view all such properties in chrome web console
Upvotes: 0
Reputation: 125630
There is parentNode
property within element
, so you can do following:
var parent = document.getElementById('shapes');
var child = document.getElementById('star');
var isChild = false;
var current = child;
while(current = current.parentNode)
{
if(current == parent)
isChild = true;
}
It will return true if parent
element is somewhere over child
element within DOM - not only when it's directly its parent.
Upvotes: 2
Reputation:
Check the .parentNode
of the child.
if (child.parentNode === parent) {...
Upvotes: 9