Today is a good day to code

IE JavaScript Again Different for nextSibling

Posted: December 31st, 1969 | Author: | Filed under: Uncategorized | No Comments »

IE JavaScript Again Different for nextSibling

Picture of IrvinThe other day I was working on a project in which the wonderful node property nextSibling was required. Technically this property breaks encapsulation since the node really should know nothing about its sibling nodes. Java does it properly having the document control node position, but it makes operations like nextSibling difficult to implement. So I prefer JavaScript's 'flawed' implementation.

When I implemented nextSibling in my application, I was trying it on an unordered list like this:

  • some text
    • more text

  • yet even more text

I had expected everything to turn out fine in IE 7, but it didn't. Since I was looking for a property of the next sibling node like:

var mySiblingNode = document.getElementById('someId').nextSibling; = “someNewClass”;

I had expected to get the ul after the li with the JavaScript function on click. The problem was that while Firefox would get the ul under the li, IE would skip the ul and get the following li. This obviously caused problems.

The reason that IE does this, or I don't know if it is a reason, but what IE does is that it grabs the nextSibling of the same node type in a node list. So my solution was to change my markup to this:

  • some text
    • some text in this ul

  • some more text

This construct makes all children of the top level ul li elements, and therefore Internet Explorer can access the true next sibling. The drawback is that you wind up with extra bullets, and some strange formatting differences between IE and every other browser.

Oh well, the formatting I can figure out easier than the functionality, so the above method wins.