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>.)


Nested links are illegal.

Links and anchors defined by the A element must not be nested; an A element must not contain any other A elements.


I had the same issue as @thinkbonobo and found a way to do it without JavaScript:

.outer {
  position: relative;
  background-color: red;
}
 
.outer > a {
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}
 
.inner {
  position: relative;
  pointer-events: none;
  z-index: 1;
}
 
.inner a {
  pointer-events: all;
}
<div class="outer">
  <a href="#overlay-link"></a>
  <div class="inner">
    You can click on the text of this red box. It also contains a
    <a href="#inner-link">W3C compliant hyperlink.</a>
  </div>
</div>

The trick is to make an anchor covering the whole .outer div, then giving all other anchors in the inner div a positive z-index value. Full credit goes to https://bdwm.be/html5-alternative-nested-anchor-tags/