Thursday, 2 October 2008

JavaScript and Html Not-Comments

Here’s a puzzle for your Mum, Grandma or beloved

Take one scoop of HTML

<body>
<!--element 1 -->
<div id="element1">Content</div>
<!-- element 2 -->
<div id="element2">Content</div>
</body>

And run a cheeky sprinkle of JavaScript against it


Var element = document.getElementById("element2").previousSibling
Alert(element);

Which element do you hit?

You don’t need to be a Web developing genius to work out that it going to pickup the div element2 then navigate back one so it will hit div element1. Easy! Welll – not really – it actually navigates to the comment. The alert spits out

<!-- element 2 -->

So if you’re navigating the JavaScript DOM that can be a real gotcha. What I found particularly interesting is that this code totally breaks my mental model of how all programming/scripting/markup languages work i.e. comments never count. They’re not included in binaries, they don’t count for code coverage analysis, they don’t display on the UI. Comments never count – except when they do.

No comments: