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>
source share