简体   繁体   English

我想在没有jQuery的情况下从javascript附加html

[英]I want to append my html from javascript without jQuery

.appendChild is not working for me, all I want to do is append the html code in my javascript const bottomText to the DOM without jQuery .appendChild对我不起作用,我要做的就是将我的javascript const bottomText中的html代码附加到没有jQuery的DOM中

   const bottomText = `
        <div class="bottom-text row">
          <div class="column column-left">test
            <p>xx%<span></span></p>
          </div>
          <div class="column column-right">
          <p>test</p>
          </div>
        </div>
        <hr>
        `;
document.getElementById("piechart").appendChild(bottomText);

And my html 和我的HTML

<body>
    <div class="graphs">
        <div class="pie-chart" id="piechart">
        </div>
        <script src="./js/pie.js"></script>
        <script src="./js/linegraph.js"></script>
    </div>
</body>

Why does it not work? 为什么不起作用? with jquery it works but for this project they want me to only use vanilla js 与jQuery的作品,但对于这个项目,他们希望我只使用香草JS

appentChild() takes a Node as a parameter. appentChild()将Node作为参数。 If you want to add string containing you can use insertAdjacentHTML() 如果要添加包含的字符串,则可以使用insertAdjacentHTML()

document.getElementById("piechart").insertAdjacentHTML("beforeend",bottomText);

MDN Docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML MDN文件: https//developer.mozilla.org/zh-CN/docs/Web/API/Element/insertAdjacentHTML

You can use .insertBefore() 您可以使用.insertBefore()

There is no insertAfter() method. 没有insertAfter()方法。 It can be emulated by combining the insertBefore method with Node.nextSibling. 可以通过将insertBefore方法与Node.nextSibling结合使用来模拟它。

 function myFunction() { var node = document.createElement('li'); node.innerHTML = '<strong>Water</strong>' var list = document.getElementById("myList1"); list.insertBefore(node, list.childNodes[0]); } 
 <ul id="myList1"> <li>Coffee</li> <li>Tea</li> </ul> <p>Click the button to move an item from one list to another</p> <button onclick="myFunction()">Try it</button> 

To use .appendChild() for first you should create an element: 首先要使用.appendChild() ,您应该创建一个元素:

let element = document.createElement("div");
    document.body.appendChild(element);

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

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