Lurking in the shadows of the Stack Overflow website, selling aerosol cans of Bug-No-More to the rubes, I came across a question I thought I could answer. The OP (original poster) was using JavaScript to select and modify HTML elements without success.
The HTML was simple:
<ul>
<li><a href="#" id="prev">Prev</a></li>
<li><a href="#" id="middle">Middle</a></li>
<li><a href="#" id="next">Next</a></li>
</ul>
First he created a simple function to make sure the basics were working (a very good practice). It colored the middle li element and it worked fine:
function middle()
{
document.getElementById("middle").parentNode.style.backgroundColor = "yellow";
}
- get the middle element using its id (an a tag)
- move up one element via the parentnode (to the li)
- color the li
Next, he created a function to color the siblings of the middle element.
- get the middle element using it's id (an a tag)
- move up one element via the parentnode (to the li)
- get the previous/next sibling
- color the li
function prevNextSibling()
{
document.getElementById("middle").parentNode.previousSibling.style.backgroundColor = "pink";
document.getElementById("middle").parentNode.nextSibling.style.backgroundColor = "cyan";
}
It didn't work.
When I debugged the code, I saw that nextSibling was returning an object that did not have a style property. What the heck was up with that?
In FireFox the debugging window looked like this:
In Chrome the debugging window looked like this:
In Internet Explorer the debugging window looked like this:
Hey, what the heck are those "Text = Empty Text Nodes" in the Internet Explorer window? What they are, my curious friend is the cause of the problem: nextSibling and previousSibling are returning Empty Text Nodes which do not have a style attribute.
To be perfectly clear:
- ALL three browsers have Empty Text Nodes.
- ONLY Internet Explorer displays them in its debugger.
Internet Explorer is the best browser in this situation.
So what are these Empty Text Nodes?
http://www.w3.org/DOM/faq.html#emptytext
And what is the fix?
If the siblings are the same type, as they are in the original problem, use:
prevElementSibling
nextElementSibling
Otherwise, move two siblings to skip over the Empty Text Node sibling:
previousSibling.previousSibling
nextSibling.nextSibling
Either way, it works:
Oooh, pretty.
So, in addition to learning about white space nodes in the DOM, we learned that having multiple browsers installed can be a good thing.
I hope someone finds this useful.
Steve Wellens
CodeProject