Home > Software engineering >  Can't add text node to div class using appendChild and getElementById
Can't add text node to div class using appendChild and getElementById

Time:06-09

trying to add text to an existing div element using a script. It should add text to the element with the id "TopBarContainer, but nothing happens when I run the script.

I tested out creating the text and just adding it to the document body whenever the script is run to make sure it is not an issue with the script call, or the creation of the text/text container and this worked fine.

I am very new to html and javascript. This seems like it should be very simple, but I've looked at the tutorial on W3, searched on stack overflow, and looked at some info on the appendChild and getElementById and wasn't able to figure out what I missed.

The relevant part of the script:

<div  id= "TopBarContainer">
    <img src="webibarmax.png" id="topbar" title="The bar" alt="Superbar">
</div>

<script>
    myScript() {
    var TextContainer = document.createElement("p");
    var TextItem = document.createTextNode("textextext");
    TextContainer.appendChild(TextItem);

    document.getElementById("TopBarContainer").appendChild(TextContainer);
        

    document.body.appendChild(TextContainer);}

</script>

CodePudding user response:

var TextContainer = document.createElement("p");
var TextItem = document.createTextNode("textextext");
TextContainer.appendChild(TextItem);

document.getElementById("TopBarContainer").appendChild(TextContainer);
document.body.appendChild(TextContainer);
<div  id="TopBarContainer">
    <img src="webibarmax.png" id="topbar" title="The bar" alt="Superbar">
</div>

As you can see from the snippet above, your code seems to be working fine.

According to the documentation you can't reference the same node twice as you are doing in your example (once in the div and another time in the body:

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position

Could that be the issue you are having?

CodePudding user response:

var TextContainer = document.createElement("p");
var TextItem = document.createTextNode("textextext");
TextContainer.appendChild(TextItem);

document.getElementById("TopBarContainer").appendChild(TextContainer);

You don't need append TextContainer element to the body.

  • Related