code snippet from DOM Scripting

From Chapter 9: CSS-DOM.

A neat example on how to target elements in relation to their siblings. The following may be used to attach specific presentation to the element following another specific element. The example given is “the element immediately following an h2”. I like this; reminds me of the proposed section element in XHTML2. Headers are semantically associated with the content that follows, and often there are presentational implications as well.

This is also similar to the CSS pseudo-classes “first-child” and “last-child”.. which are not widely supported in modern browsers. This is a way to achieve those effects while browsers catch up.

Code:

function getNextElement(node) {
  if (node.nodeType ==1) {
      return node;
  }
  if (node.nextSibling) {
     return getNextElement(node.nextSibling);
  }
  return null;
}


And the code they used that called this one:


function styleHeaderSiblings() {
 if (!document.getElementsByTagName) return false;
 var headers = document.getElementsByTagName("h2");
 for (var i = 0; i < headers.length; i++) {
   var elem = getNextElement(headers[i].nextSibling);
   addClassName( elem, "intro");
 }
}

Thoughts: Can this help with setting up tabs, etc? Although we seem to be moving towards the sliding doors tabs, what about using this to determine if you are at the first or last tab, and load the appropriate image accordingly?

.......

And as I read further...
The book then goes onto talking about abstraction. The styleHeaderSiblings function is very specific, it deals with h1s and the classname "intro". This should really be made more generic so it is reusable. We really should modify it to take in a tag and classname as arguments.


function styleElementSiblings(tag, theclass) {
 if (!document.getElementsByTagName) return false;
 var headers = document.getElementsByTagName(tag);
 for (var i = 0; i < headers.length; i++) {
   var elem = getNextElement(headers[i].nextSibling);
   addClass(elem, theclass);
 }
}

I should also store this somewhere.. and here seems as good a place as any!


function insertAfter(newElement, targetElement) {
  var parent - targetElement.parentNode;
  if (parent.lastChild == targetElement) {
     parent.appendChild(newElement);
  } else {
     parent.insertBefore(newElement, targetElement.nextSibling);
  }
}