0

Say I have an HTML file with the following code:

<foo>
    <bar id="bar1"></bar>
    <bar id="bar2"></bar>
    <bar id="bar3"></bar>
</foo>

<script>
    const foo = document.getElementsByTagName("foo")[0];
    const bars = foo.children;
    for (i = 0; i < bars.length; i++) {
        console.log(bars[0]);
    }
</script>

Running it in a browser (in my case, Chrome) results in the three bar nodes being printed on the console, which is the expected behavior.

However, when I shorten the notation for bar nodes as follows

<foo>
    <bar id="bar1" />
    <bar id="bar2" />
    <bar id="bar3" />
</foo>

the number nodes printed becomes only one. And it seems that, bar2 is the child of bar1, and bar3 is the child of bar2.

Does HTML DOM handle empty elements differently?

Yuhuan Jiang
  • 2,616
  • 2
  • 19
  • 21
  • Please use valid HTML, there's no guarantee of how a browser will behave when you give it garbage. – zer00ne Nov 26 '16 at 05:09

1 Answers1

0

The /> notation has no meaning in HTML. It only has meaning in XML.

As far as the HTML DOM is concerned, in your second example you have three bar elements (which are unrecognized, might I add) that are nested within one another, with missing end tags, making it equivalent to the following:

<foo>
    <bar id="bar1">
        <bar id="bar2">
            <bar id="bar3"></bar>
        </bar>
    </bar>
</foo>

In other words, you don't actually have empty elements in your second example (with the exception of #bar3) — because /> is meaningless in HTML, it doesn't represent an end tag like it does in XML.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • However, I find that W3Schools is saying otherwise http://www.w3schools.com/html/html_elements.asp. You can search for "Empty HTML Elements" in the page. – Yuhuan Jiang Nov 26 '16 at 04:24
  • @Yuhuan Jiang: W3Schools grossly oversimplifies things. It assumes you're using standard elements that *are* recognized as void elements. But the /> notation itself doesn't actually have any meaning; it's only allowed in HTML5 as a convenience to authors migrating from XHTML. Since "bar" isn't an actual HTML element, all the HTML processor sees is a start tag that's missing an end tag. – BoltClock Nov 26 '16 at 04:25
  • Do you mean `\>` is not a general notation, and there is a fixed set of elements like `
    `?
    – Yuhuan Jiang Nov 26 '16 at 04:27
  • @Yuhuan Jiang: Yes, in HTML; see also [Are void elements and empty elements the same?](http://stackoverflow.com/questions/25313426/are-void-elements-and-empty-elements-the-same) – BoltClock Nov 26 '16 at 04:28