Lost link node? (Javascript)

So, I have this JS code:

var pElt = document.createElement("p"); var aElt = document.createElement("a"); aElt.textContent = "Text"; aElt.href = "#"; pElt.appendChild(aElt); aElt.style.color = "red"; pElt.innerHTML += "<span> and more text</span>"; //aElt.style.color = "red"; document.getElementById("content").appendChild(pElt); console.log(aElt); // always show the red attribute 

There is probably some answer here, but I can’t even describe the problem; so I went with the “lose link node”, although this is not what happens here. (edit: really, what’s going on here is stupid :))

So ... Please try the code as it is. It works, the link is red, everyone is happy. Now comment on "aElt.style.color =" red ";" line, then uncomment the other, two lines below.

... This does not work, the link is still displayed in black. I thought the pointer associated with my node was either invalid or aElt was moved to a different memory address. But when I type "console.log (aElt)", it outputs node correctly (well ... I think it is), so I don’t understand why I cannot access it after changing .innerHTML.

I'm interested in what happens under the hood :)

Thanks!


index.html:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Question!</title> </head> <body> <div id="content"></div> <script src="script.js"></script> </body> </html> 
+5
source share
1 answer

When you overwrite the contents of the <p> element by setting it innerHTML , you actually turn the <a> back into HTML text by adding a <span> (like text) and then re-creating the new DOM of the nodes in the <p> . Your previous link still refers to the original <a> you created.

Instead, you can create this <span> just like you created <a> , and add a node to <p> instead of overwriting .innerHTML .

+8
source

Source: https://habr.com/ru/post/1263453/


All Articles