Yash Shukla
Yash Shukla

Reputation: 32

why href not working when anchor is dynamically created inside another anchor?

Scenario 1 :

I have an anchor with onclick="return false;" and then I am adding another anchor inside it dynamically. The href is not working when the parent anchor has onclick="return false;" but it works fine when i remove that onclick.

<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
 <head></head>
  <body>
    <a id="link1" onclick="return false;"></a>
    <script>
       var link = document.getElementById('link1')
       var newLink = document.createElement('a')
       newLink.setAttribute('href','https://wwww.google.com')
       newLink.innerHTML="google"
       //link.insertAdjacentElement('beforeend', newLink)
       link.appendChild(newLink)
    </script>
 </body>
</html>

Scenario 2 :

I just have two anchors with parent anchor having onclick as return false. but in this case the inner anchor's href works fine.

<a onclick="return false;"><a href="https://www.google.com">google</a></a>

So the problem is, when I am adding anchor dynamically inside another anchor with onclick as return false then the inner anchor's href is not working but it is working fine when they are statically created.

Can anybody please help me understand this behavior?

Upvotes: 0

Views: 1066

Answers (1)

Daut
Daut

Reputation: 2625

The browser doesn't parse it nested as you expect, but JavaScript manages to get in nested.

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.

Upvotes: 2

Related Questions