javascripthtmlwebfrontend

After Changing the text Content of an H# element can't access a constant that was assigned to a span,even after returning the innerHTML back to normal


I started learning web development not too long ago and I stumbled upon an issue.

It goes as follows:

1.I have an H# element with a span(with an id)

2.I assigned a constant to the span.

3.I changed the H element's textContent to show a different result.

4.I changed the InnerHTML of the H element back to the original format.

5.I assigned a new text content to the constant from step #2.

6. I tried to debug.log the H element and the span element cannot be changed.

assume exists:
    <h2 id="h2-id">Some text:<span id="span-id">Content</span>!</h2>

Example:
const result = document.querySelector("#span-id");
const resultText = document.querySelector("#h2-id");
resultText.textContent = "Something else.";
resultText.innerHTML = 'Some text:<span id="span-id">Content</span>!';
result.textContent = "New Content";
debug.log(resultText.textContent);//prints: Some text:Content! not Some text:New Content!.

It works if I assign the (previously)constant as a regular variable and query it again after restoring the InnerHTML, tho I do not understand since it was queried initially by an ID isn't it supposed to "re-attach" to the H element after I restore Its contents?

I assume js looks at the reassigned innerHTML as a new "Object" so it doesn't recognize it?


Solution

  • As said in some of the comments, setting innerHTML overwrites what was previously on the DOM and the result variable points to a node that no longer exist.

    A way around this (for this specific use case) would be to use a function. Something like

    
    function getSpan() {
      return document.querySelector("#span-id");
    }
    
    getSpan().textContent = "New Content";
    

    This way, calling the getSpan() function will always check the DOM for the span and not use what was already stored in memory.