Creating anchor tag inside anchor tag

As @j08691 describes, nested a elements are forbidden in HTML syntax. HTML specifications do not say why; they just emphasize the rule.

On the practical side, browsers effectively enforce this restriction in their parsing rules, so unlike in many other issues, violating the specs just won’t work. The parsers effectively treat an <a> start tag inside an open a element as implicitly terminating the open element before starting a new one.

So if you write <a href=foo>foo <a href=bar>bar</a> zap</a>, you won’t get nested elements. Browsers will parse it as <a href=foo>foo</a> <a href=bar>bar</a> zap, i.e. as two consecutive links followed by some plain text.

There is nothing inherently illogical with nested a elements: they could be implemented so that clicking on “foo” or “zap” activates the outer link, clicking on “bar” activates the inner link. But I don’t see a reason to use such a structure, and the designers of HTML probably didn’t see one either, so they decided to forbid it and thereby simplify things.

(If you really wanted to simulate nested links, you could use a normal link as the outer link and a span element with a suitable event handler as the inner “link”. Alternatively, you could duplicate links: <a href=foo>foo</a> <a href=bar>bar</a> <a href=foo>zap</a>.)

Leave a Comment