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.


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="" id="theA">Wired</a>
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.


Tags: code javascript

Authorized users may log-in to leave a comment.

Last Blog: Installing CS3 From Hard Disk

Next Blog: On URIs.