removeAllChildNodes, getImmediateChildren (JavaScript)

Two functions for working with nodes via the W3C DOM (while they have only been tested on web pages, there is no reason why they won't work (with minor modifications) with anything that implements the W3C DOM and uses JavaScript/ECMAScript).

function removeAllChildNodes(node)
{
  if(!node || !node.childNodes) return;
  var nodeCount = node.childNodes.length;
  for(var i=nodeCount-1;i>=0;i--)
  {
    node.removeChild(node.childNodes[i]);
  }
}
function getImmediateChildren(node, tagName)
{
  if(!node || !node.childNodes) return;
  if(!tagName) tagName = "*";
  var elements = document.getElementsByTagName(tagName);
  var nodeCount = elements.length;
  var children = new Array();
  for(var i=0;i<nodeCount;i++)
  {
    if(elements[i].parentNode == node)
    {
      children[children.length] = elements[i];
    }
  }
  return children;
}

Imagine the following HTML:

<div id="foo">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3
      <ul>
        <li>Item 3.1</li>
        <li>Item 3.2</li>
      </ul>
    </li>
    <li>Item 4</li>
  </ul>
</div>

If you then did removeAllChildNodes(document.getElementById("foo")) you would end up with an empty <div id="foo"></div>.

var foo = document.getElementById("foo");
var ul = foo.getElementsByTagName("ul")[0];
var ulitems = getImmediateChildren(ul, "li");

Would return the list items Item 1, Item 2, Item 3 and Item 4 (not Item 3.1 and Item 3.2 as they are not directly descended from ul)


Tags: ,

Comments

Popular posts from this blog

Select box manipulation with jQuery

iTextSharp: Generating a Basic PDF file (ASP.NET/C#)

Popup Window Countdown (JavaScript)