Go to content Go to menu

getChildrenByTagName

Thu Aug 3, 13:51

Until the day we can use javascript select elements with XPath (natively) this script will be useful.

Select all children (not descendants) that have a specified tag name.

E.g. getChildrenByTagName( $('navigation'), 'li' ) will only select li elements that are children of your <ul id="navigation"> element. Note that the $(..) function is provided by the Prototype library.
function getChildrenByTagName(root_element, tag) {
  var kids = root_element.childNodes

  var kids_w_tag = new Array()
  
  for (var i=0; i<kids.length; i++)
    if (kids.item(i).tagName == tag.toUpperCase())
      kids_w_tag.push(kids.item(i))
      
  return kids_w_tag
}

This is useful because some browsers (including FF) correctly include white-space between elements in the DOM as TextNodes.

For example:

<ul>
 <li>Harry</li>
 <li>Susan</li>
</ul>

The child nodes of the ul above are [ TextNode, LIElement:Harry, TextNode, LIElement:Susan, TextNode ]

<ul><li>Harry</li><li>Susan</li></ul>

But in this example, the childnodes of the ul are [ LIElement:Harry, LIElement:Susan ]