Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

How to find and access parent nodes via JavaScript

June 26th, 2008  |  Published in javascript


Have you ever had to access a parent node from a given child node? In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the name attribute itsMe.


Demo

My name is notMe

My name is itsMe

My name is notMeEither

My name is tryAgain

My name is sorryNotMe

My name is nopeSorry



Here is the HTML code. It’s just a series of embedded div elements with different names and the input button where we start to traverse up the DOM tree accessing each parent node and asking for it’s name attribute value. The onClick event of the button triggers the findParentNode and passes the name of the element we are looking for and the object itself which, in this case, is the button. This is the starting point where we will begin traversing up the DOM tree by accessing the parent nodes of each element and seeing if the name attribute matches what we are looking for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div name="notMe" style="padding:10px;border:1px solid green;">
My name is <b>notMe</b>
    <div name="itsMe" style="padding:10px;border:1px solid blue;">
    My name is <b>itsMe</b>
        <div name="notMeEither" style="padding:10px;border:1px solid red;">
        My name is <b>notMeEither</b>
            <div name="tryAgain" style="padding:10px;border:1px solid purple;">
            My name is <b>tryAgain</b>
                <div name="sorryNotMe" style="padding:10px;border:1px solid black;">
                My name is <b>sorryNotMe</b>
                    <div name="nopeSorry" style="padding:10px;border:1px solid brown;">
                    My name is <b>nopeSorry</b>
                        <input type="button" value="Find Parent Object with name=itsMe" onClick="findParentNode('itsMe', this);">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Here is the findParentNode JavaScript code:

1
2
3
4
5
6
7
8
9
10
11
function findParentNode(parentName, childObj) {
    var testObj = childObj.parentNode;
    var count = 1;
    while(testObj.getAttribute('name') != parentName) {
        alert('My name is ' + testObj.getAttribute('name') + '. Let\'s try moving up one level to see what we get.');
        testObj = testObj.parentNode;
        count++;
    }
    // now you have the object you are looking for - do something with it
    alert('Finally found ' + testObj.getAttribute('name') + ' after going up ' + count + ' level(s) through the DOM tree');
}

In line 2, we access the parent node of the child element via the parentNode method which is the first div above the button named nopeSorry. We then begin a count of the number of times we traversed up the DOM tree and set it to 1 because we have already accessed the parent node once. The while loop will test if the name of the current node will match the name that we are looking for. If not, it moves up the DOM tree by accessing the next parent node and continues to look for the right name while increasing the count by 1 each time. Once it finds the right node, the function exits the while loop and alerts the node name along with the number of times it traversed up the DOM tree.

If you do not know the name of the parent element you are looking for you can also search using the tagName method. The tagName will return the value of the tag name of the given node such as A or DIV.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • drei on Simulate a button click via JavaScript
  • Subhee on How to count values with MySQL queries
  • Russell Day on How to hide, show, or toggle your div
  • phi on How to hide, show, or toggle your div
  • bornholy on How to hide, show, or toggle your div

Archives

Categories

  • javascript
  • mysql
  • php

Tag Cloud

add addition and subtraction calculator checkboxes checkEmail content demo demo content div id document getelementbyid dynamic Dynamically dynamic content emailRegEx find form getElementById html javascript input buttons input object input text javascript javascript code javascript demo javascript email javascript function javascript functions loop through menu multiplication mysql mysql query onClick onclick event query regex remove removeChild removeElement replace simulate styling valid email address verification verifyEmail

©2010 Random Snippets