Getting to the next element

Traversing the HTML DOM to get to the next element can be a tricky business.

Take the following list as an example:

<ul>
    <li>First item</li>
    <li>Second item</li>
    <li>Third item</li>
</ul>

Internet Explorer considers that there are only three nodes within the UL tag (the LI elements), whereas virtually all other modern web browsers consider that there are seven nodes within the UL element.

Three of the nodes are the LI elements, and the other four are text nodes, the whitespace between the tags, which consists of spaces, tabs, and newlines.

Text elements can also easily be normal text though. Consider the following:

<p>Some text with <a href="link.html">a link</a>.</p>

This paragraph contains two text nodes and an A element, which itself contains a text node.

#text "Some text with "
A
  #attr href="link.html"
  #text "a link"
#text "."

It is this difference between modern web browsers and Internet Explorer, that causes trouble when using direct node relationships such as the nextSibling property.

In many cases you can avoid this problem by using other techniques. With the unordered list for example, you can assign the UL element to a variable called el and use document.getElementsByTagName('li') to get all of the LI elements.

There can be times though when you need to step forward to the next element and avoid text nodes. As the nodeType of text elements is 1, and the nodeType of HTML tags is 3, we can use that as the basis for a useful tool.

function nextElement(el) {
    el = el.nextSibling;
    while (el && el.nodeType === 1) {
        el = el.nextSibling;
    }
    return el;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: