如何使用javascript在html页面中动态创建元素?

我正在学习使用 javascript 在 html 页面中动态创建一个元素。在这段代码中,我试图在“div-1”中创建一个简单的“h6”。


<!DOCTYPE html>

    <header>

        <meta charset="utf-8">

    </header>

    <body>

        <button onclick="constructElement()">click</button>

        <div id="div-1"></div>


        <script>

            function constructElement(){

                var elem = document.createElement("h6");

                elem.innerText("Dynamically added text.")

                document.getElementById("div-1").appendChild(elem);

            }

        </script>

    </body>

</html>


森栏
浏览 164回答 3
3回答

慕妹3146593

<header>&nbsp; &nbsp; <meta charset="utf-8"></header><body>&nbsp; &nbsp; <button onclick="constructElement()">click</button>&nbsp; &nbsp; <div id="div-1">&nbsp; &nbsp; </div>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function constructElement(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var elem = document.createElement("h6");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elem.innerText= "Dynamically added text.";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("div-1").appendChild(elem);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></body>

九州编程

设置节点的文本内容:node.innerText = textfunction constructElement(){&nbsp; &nbsp; var elem = document.createElement("h6");&nbsp; &nbsp; elem.innerText ="Dynamically added text."&nbsp; &nbsp; document.getElementById("div-1").appendChild(elem);}

慕斯王

您的代码中有两个错误,第一个是您使用了错误的“id”名称 div-1 而不是 div1,innerText 不是函数这是修复后的代码:)<header>&nbsp; <meta charset="utf-8"></header><body>&nbsp; <button onclick="constructElement()">click</button>&nbsp; <div id="div-1">&nbsp; </div>&nbsp; <script>&nbsp; &nbsp; function constructElement() {&nbsp; &nbsp; &nbsp; var elem = document.createElement("h6");&nbsp; &nbsp; &nbsp; elem.innerText = "Dynamically added text."&nbsp; &nbsp; &nbsp; document.getElementById("div-1").appendChild(elem);&nbsp; &nbsp; }&nbsp; </script></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript