I'm trying to write a function that takes an ID then traverses up the DOM to see if that item is a child of a tag. This shouldn't be too hard however my parentNode
is coming back as undefined
? What am I missing?
Here's a simplified version of my code... thanks in advance.
<!DOCTYPE html>
<html lang="en">
<body>
<div id="top">
<div id="top2"></div>
<div id="top3"></div>
<div id="top4"></div>
<div id="top5">
<div id="top5_1"></div>
</div>
<div id="top6">
<div id="top6_1">
<a href="" id="findMe">here I am...</a>
</div>
</div>
</div>
<script>
function findParent(startID, finish){
// change this from id to tag
start = document.getElementById(startID).tagName;
while (start.parentNode) {
start = start.parentNode;
if (start.tagName === finish){
console.log("true " + startID + " is a child of " + finish);
}else{
console.log("false " + startID + " ISN'T a child of " + finish);
}
}
}
findParent("findMe", "BODY");
</script>
</body>
</html>
Things to note when using the parentNode property: Trying to access the parentNode property on a Document or DocumentFragment nodes returns null - they can never have a parent. The property returns null if the HTML element has been created but not yet attached to the DOM.
A Node that is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.
Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.
parentNode is native JS, where parent() is not. What you are doing in your code is wrapping the DOM elements in the jQuery object so you can call jQuery specific methods on it. So, you cannot call index() on just this. parentNode, but you can call it on $(this. parentNode).
The problem is:
start = document.getElementById(startID).tagName;
while (start.parentNode) {
start = start.parentNode;
You trying to get the parentNode
from the tagName
, which is a string.
Remove the tagName
, and you should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With