Re: childElements, childElementCount, and children

> I don't feel too strongly about having both .children and .childElements,
> but I do think that .children is a little problematic for authors... they
> will always have to check to see if Comment nodes are included, because of
> the large marketshare for older versions of IE, while .childElements allows
> them to write simple, clean, efficient code, which is the whole point of an
> element-based API.

That's not completely true - if a code base were to make use of
.children for efficiency it would probably write code like the
following:

var getChildren = (function(){
  var div = document.createElement("div");
  div.innerHTML = "<!--div-->";
  if ( div.children && div.children.length === 0 ) {
    return function(elem){
      return elem.children;
    };
  } else {
    return function(elem){
      var ret = [], child = elem.children || elem.childNodes;
      for ( var i = 0, l = child.length; i < l; i++ ) {
        if ( child[i].nodeType === 1 ) {
          ret.push( child[i] );
        }
      }
      return ret;
    };
  }
})();

That way they'd have one clean function for .children in browsers that
handle it nicely and another for ones that don't.

In comparison, the following is a sample of the code that would need
to exist to use .childElements

var getChildren = (function(){
  if ( document.documentElement.childElements ) {
    return function(elem){
      return elem.childElements;
    };
  } else {
    return function(elem){
      var ret = [], child = elem.children || elem.childNodes;
      for ( var i = 0, l = child.length; i < l; i++ ) {
        if ( child[i].nodeType === 1 ) {
          ret.push( child[i] );
        }
      }
      return ret;
    };
  }
})();

In the end, not much of a change - at least not enough to warrant a
completely new property. (Note: The above code aggregates an array of
DOM elements, it's likely that you would want to avoid the extra loop
in a high performance situation. Also, elem.children ||
elem.childNodes is used to get a minor perf boost in IE, since it'll
have to search through less nodes. Also, if .childElements did exist
it's likely that some code bases would start to have an if (
childElements ) {} else if ( children ) {} else {} - which wouldn't
make a ton of sense if IE never implements the new property.)

--John

Received on Wednesday, 21 October 2009 01:33:23 UTC