JAVA SCRIPT - Accessing a Given Element and Finding Its Parent and Child Elements

Accessing a Given Element and Finding Its Parent and Child Elements 


You want to access a specific web page element, and then find its parent and child elements.


Give the element a unique identifier:

This is text.
Use document.getElementById() to get a reference to the specific element:

var demodiv = document.getElementById("demodiv");

Find its parent via the parentNode property:

var parent = demodiv.parentNode;

Find its children via the childNodes property:

var children = demodiv.childNodes;


A web document is organized like an upside-down tree, with the topmost element at the root and all other elements branching out beneath. Except for the root element (HTML), each element has a parent node, and all of the elements are accessible via the document.

There are several different techniques available for accessing these document elements, or nodes as they’re called in the Document Object Model (DOM). Today, we access these nodes through standardized versions of the DOM, such as the DOM Levels 2 and 3.

Originally, though, a de facto technique was to access the elements through the browser object model, sometimes referred to as DOM Level 0. The DOM Level 0 was invented by the leading browser company of the time, Netscape, and its use has been supported (more or less) in most browsers since. The key object for accessing web page elements in the DOM Level 0 is the document object.

The most commonly used DOM method is document.getElementById(). It takes one parameter: a case-sensitive string with the element’s identifier. It returns an element object, which is referenced to the element if it exists; otherwise, it returns null.

The returned element object has a set of methods and properties, including several inherited from the node object. The node methods are primarily associated with tra‐ versing the document tree. For instance, to find the parent node for the element, use the following:

var type = parent.nodeName; // BODY

If you want to find out what children an element has, you can traverse a collection of them via a NodeList, obtained using the childNodes property:

"has child #text has child P has child #text "

You might be surprised by what appeared as a child node. In this example, whitespace before and after the paragraph element is itself a child node with a nodeName of #text. For the following div element:

has child #text
has child P
has child #text
has child P
has child #text

The best way to see how messy the DOM can be is to use a debugger such as Firebug or the Chrome developer tools, access a web page, and then utilize whatever DOM in‐ spection tool the debugger provides.

 I opened a simple page in Chrome and used the developer tools to display the element tree.


Post a Comment