parentNode

Creator:
Peter
Description:
Small tutorial covering how parentNode works.

parentNode is used to get the most outer node, think of parentNodes as containers, in the container you have child nodes, to see what I mean, take a look at the example below.

<div id="parent">
<b id="child">My text</b>
</div>

With the little snippet of HTML above, you have the parent node being a div container, in that container you have "child", that child being a bold element. If you were to grab the bold element by the id (getElementById()) and ask what its parent node is, the information sent back to you would be a div. Check the script below which gives you an example of how to do this.

<div id="parent">
<b id="child">My text</b>
</div>
<script type="text/javascript">
<!--
alert(document.getElementById("child").parentNode.nodeName);
//-->
</script>

With that script above we are telling the script to tell us what the node name is of the parent. So when we run the script, what happens is that we will get an alert box with the name of the parent element, which will be "div", if we didn't use nodeName after parentNode, we wouldn't be able to tell what the element is, all you would get is "[object]". With parentNode you aren't just limited to finding 1 parent,

child nodes can also be parents, take a look at the example below.

<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>

With the above HTML we have 2 parents and 2 childs. The first div "parent" is a parent of the second div that is nested inside, so the second div is a child of "parent". Inside "childparent" we have the bold element "child", this is now a child of "childparent". So how do we access the childs parent parent element? Simple, check the script below.

<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>
<script type="text/javascript">
<!--
alert(document.getElementById("child").parentNode.parentNode.nodeName);
//-->
</script>

Notice the 2 parentNode's? "parentNode.parentNode". The first parentNode is the div with the id "childparent", because we want to get the most outer parent element, we need to go out even further, so by adding another parentNode we reach the div with the id "parent".

With parentNode you aren't limited to just finding an elements nodeName, you can do more then that, for example, you could grab the parent node which contains the bold element, and then append a new node onto the end. Internet Explorer comes with its own version called parentElement, but for cross browser scripts I suggest you keep with parentNode.

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <u> <i> <hr> <img src <url=
  • Lines and paragraphs break automatically.

More information about formatting options