0
<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <script type="text/javascript">
        function fire() {
            console.log(document.body.children.length);
            console.log(document.body.children[0].children.length);
        }
    </script>
    <body onload="fire()">
        <div>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pharetra ipsum erat. Aenean convallis laoreet massa, et gravida purus faucibus ac. <a id="test"/>Vestibulum libero justo.</p>
        </div>
    </body>
</html>

When you open the console, you'll see that the <a> is a children of <body>, <div> and <p>. WTF??

If <a> is closed with a "proper" closing tag the issue disappears and its only child of <p>.

Can someone explain this to me?

PS: Tested on Chrome stable.

Aron Woost
  • 15,276
  • 12
  • 39
  • 49
  • 6
  • 1
    Explained here: http://stackoverflow.com/questions/97522/what-are-all-the-valid-self-closing-tags-in-xhtml-as-implemented-by-the-major-b – Diodeus - James MacFarlane Mar 12 '12 at 15:43
  • Would it work when served with Content-Type "application/xhtml+xml"? – Aron Woost Mar 12 '12 at 15:50
  • If you mean, would it self-close, and you'd not get the extra `a` elements when served with Content-Type `application/xhtml+xml`, then the answer is yes it would. And in spite of what Matthew says, it would indeed be valid XHTML5 (more formally, HTML5 in the XML serialization). You'd need to add the correct namespacing attribute to the html element though. – Alohci Mar 12 '12 at 17:14
  • 1
    As a demonstration, here is your test case served as application/xhtml+xml: http://www.alohci.net/application/xhtml+xml/aron.htm.ashx . Notice in a Dom inspector that the `a` element does not "break out". – Alohci Mar 12 '12 at 21:07
  • @Alohci Thanks for the explanation and the testcase! – Aron Woost Mar 13 '12 at 11:23

5 Answers5

8

I imagine it's because a is not a valid short tag.

Matthew
  • 21,467
  • 5
  • 66
  • 95
3

As per the W3C recommdentations:

12.2 The A element [...] Start tag: required, End tag: required

It is invalid HTML. You need to at least close the tag directly after such as <a id="test"></a>.

Source: http://www.w3.org/TR/html401/struct/links.html

Rémi Breton
  • 4,030
  • 2
  • 20
  • 33
1

<a> tags require an end tag (</a>).

<a /> is invalid, and browsers will try to figure out what you mean, but don't expect consistent behavior.

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
1

From w3schools.com/tags/default.asp you can see self ending tags:

"area", "base", "basefont", "br", "col", "frame", "hr", "img", "input", "link", "meta", "param"

The A tag should not be self closed.

Michael Laffargue
  • 9,799
  • 6
  • 39
  • 74
1

This is html5, not xml. Only void elements are allowed to have such representation. Also see 8.1.2.1 part 6

kirilloid
  • 12,843
  • 5
  • 36
  • 50