簡體   English   中英

如何使用 JavaScript 創建 html 元素並為其創建類/ID

[英]How to create html element using JavaScript and create class/id to it

我想使用 JavaScript 創建 html 元素並添加 class 或 id,以便稍后編輯此元素。

我知道如何創建元素:

 <html> <body> <div id="new"> <p id="p1">a</p> <p id="p2">b</p> </div> <script> var tag = document.createElement("p"); var text = document.createTextNode("c"); tag.appendChild(text); var element = document.getElementById("new"); element.appendChild(tag); </script> </body> </html>

但我不知道如何在開始時將 class 或 id 添加到沒有 id 或 class 的元素。

你可以這樣做:

<script>
    let myP = document.createElement("p");
    // If you need change CSS you can do it like:
    myP.setAttribute("style", "color: red");
    myP.id='myP-ID'
    myP.className = 'myP-Class'
    myP.innerHTML = "SomeText for my P tag";
    document.body.appendChild(myP);
</script>

您可以添加 class:

tag.classList.add("gg");

您可以添加 class 和 ID:

tag.setAttribute("id", "ff");
tag.setAttribute("class", "bb");
you can simply target the id where you want create the element and then just create the element and give it text content and just append it ,simple.
<script>
 const parentdiv = document.querySelector(".new");
    let tag = document.createElement("p");
    tag.textContent = 'c';
    tag.id = p3;
    parentdiv.appendChild(tag);

   
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM