Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

Pew Pew Laser Blog Archives — by Blog ID

Selecting Children in the DOM.

5.8.2011

Sometimes, it's necessary to use JavaScript to walk through the HTML elements on a page. The function childNodes() function (as well as firstChild, lastChild, and previousSibling) seems like a great great way to to this. Unfortunately, it'll produce vastly different results in different browsers.

Firefox evaluates any white space in the element as a text node, so if your HTML is like this:

<div id="theDiv">
<a href="http://www.wired.com" id="theA">Wired</a>
</div>
then firstChild will be the line break. Other browsers will return the anchor element as the firstChild. Blech.

Instead, use getElementsByTagName("*"), which will get only tags. For the above HTML, this JavaScript will get the link value:

theAnchor = document.getElementById("theDiv").getElementsByTagName("*")[0];
theHref = theAnchor.getAttribute("href");
since the first element inside theDiv is the anchor.

Permalink

Tags: code javascript

Authorized users may log-in to leave a comment.

Last Blog: Installing CS3 From Hard Disk

Next Blog: On URIs.