简体   繁体   English

无法使用 appendChild 和 getElementById 将文本节点添加到 div 类

[英]Can't add text node to div class using appendChild and getElementById

trying to add text to an existing div element using a script.尝试使用脚本将文本添加到现有的 div 元素。 It should add text to the element with the id "TopBarContainer, but nothing happens when I run the script.它应该向 id 为“TopBarContainer”的元素添加文本,但是当我运行脚本时没有任何反应。

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.我对 html 和 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.这看起来应该很简单,但是我查看了关于 W3 的教程,搜索了堆栈溢出,并查看了有关 appendChild 和 getElementById 的一些信息,但无法弄清楚我错过了什么。

The relevant part of the script:脚本的相关部分:

<div class="top" 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>

 var TextContainer = document.createElement("p"); var TextItem = document.createTextNode("textextext"); TextContainer.appendChild(TextItem); document.getElementById("TopBarContainer").appendChild(TextContainer); document.body.appendChild(TextContainer);
 <div class="top" 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:根据文档,您不能像在示例中那样引用同一节点两次(一次在 div 中,另一次在正文中:

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如果给定的孩子是对文档中现有节点的引用,则 appendChild() 将其从当前位置移动到新位置

Could that be the issue you are having?这可能是您遇到的问题吗?

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.您不需要将 TextContainer 元素附加到正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM