Today I learned …

… that a whitespace within a div tag is considered a node, at least in Safari, Firefox, Chrome, and Edge but not in IE as it seems. I encountered this when I was debugging an if Statement which executed a block of code even though the specified condition, as I interpreted it, was false.

Here’s a simple example:

HTML

<div id="testdiv"> </div>

Notice the space between the opening and closing div tag

CSS

#testdiv {
  width: 100px;
  height: 100px;
  background: #ccc;
}

JavaScript

  function nodeOrNot() {


    var div = document.getElementById("testdiv");


    if (div.hasChildNodes()) {
      alert("The whitespace is a node");
    }

  }

 nodeOrNot();

Live demo

What the block of code does is to look if the <div> contains a node, and if it does, it alerts the message. In Safari, Firefox, Chrome and Edge the alert is executed, but not in IE.

If you want to read about how whitespaces are handled in browsers, then this is a good resource