Home > Blockchain >  How to create html element using JavaScript and create class/id to it
How to create html element using JavaScript and create class/id to it

Time:03-20

I want to create html element using JavaScript and add class or id, so I can edit this element later.

I know how to create element:

<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>

But I don't know how to add class or id to element that don't have id or class at beggining.

CodePudding user response:

You can do it like this:

<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>

CodePudding user response:

you can add class :

tag.classList.add("gg");

and you can add class and id :

tag.setAttribute("id", "ff");
tag.setAttribute("class", "bb");
  • Related