"parentNode" is used to grab the parent node of an element. 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">
|
|
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 which has a text node child. If you were to grab the bold element by the id using the "getElementById()" method 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">
|
|
In the code above we are telling the script to tell us what the node name is of the parent node. So when we run the script, what happens is that we will get an alert box with the name of the parent node, which will be "div", if we didn't use "nodeName" after "parentNode", we wouldn't be able to tell what type of node it is, all you would get is "[object]" in Internet Explorer, but in Mozilla FireFox you would get "[Object HTMLDivElement]", which is better then Internet Explorer.
With parentNode you aren't just limited to finding one parent, child nodes can also be parents, take a look at the example below to see what I mean.
<div id="parent">
|
|
With the above HTML we have two parents and two children. The first div with the id "parent" is a parent of the second div (childparent) that is nested inside, so the second div is a child of "parent". Inside "childparent" we have the bold element with the id "child", this is now a child of "childparent" div. So how do we access the childs parent parent element (id "parent")? Simple, check the script below.
Notice the two parentNode calls? "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 up 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.
| Discuss Tutorial: Using parentNode | 1 Comment |
has no properties
iv". You were probably expecting it to say "child". Replace "nodeName" with "id" in the script, and it will.