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?