Posts Tagged ‘text nodes’

Remove text nodes function

Wednesday, February 17th, 2010

Here’s a fairly useful function for when you’re using javascript in a web page without using  library like jQuery to take care of the nitty gritty.

It tackles problems that occur when you get the child nodes (eg myList.childNodes) of a DOM node, but there is whitespace in the html. Each of these whitespaces gets counted as a DOM node of its own, a text node, so if you run code to iterate through eg all the children of a <ul> you will find that your code throws an error as not every node is an <li> as you expected.

function removeTextNodes(nodeList) {
  list = Array.prototype.slice.apply(nodeList);
  for(var i=0, il=list.length;i<il;i++)
  {
    if(list[i].nodeType == 3)
    {
      list.splice(i,1);
      i--;
      il--;
    }
  }
  return list;
}

var myUL = document.getElementById('myUl');
var myLIs = removeTextNodes(myUL.childNodes);

I haven’t tested it in any browsers apart from firefox as I’m a bit busy, but if you find it’s buggy in Internet Explorer or elsewhere leave a comment.

(By the way, if you’re wondering about eth relevance of the image, if you search for “too many children” in flickr it throws up lots of photos of a very serious looking texas school board meeting. Too many children in Texas, apparently!).