Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating anchor tag inside anchor tag

Tags:

html

During my random testing I saw a behavior where I put an anchor tag inside another anchor tag. I made a jsfiddle.

<a class="groupPopper">      <a class="name"> content</a> </a>​ 

But in the developer tool it appears different:

enter image description here

I believe we cannot put an anchor tag inside another anchor tag as clicking on the inner anchor will bubble up the click event to the parent anchor tag which should not be allowed.

Is my assumption correct?

like image 529
Anoop Avatar asked Oct 24 '12 15:10

Anoop


People also ask

Can I add anchor tag inside anchor tag?

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.

What can go inside an anchor tag?

An anchor tag is an inline element, so it can contain other inline elements (except other anchor tags). If you want to put a block element inside an anchor, you have to use an inline element and turn it into a block element using CSS, along with the anchor tag itself.

When one tag is placed inside another tag it is called?

Answer: Explanation: Nesting. Part of the web page structure is called nesting.

Can we use tags inside other tags in HTML?

Nested HTML ElementsHTML elements can be nested (this means that elements can contain other elements). All HTML documents consist of nested HTML elements.


1 Answers

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

like image 175
Jukka K. Korpela Avatar answered Oct 13 '22 19:10

Jukka K. Korpela