'How to create html element using JavaScript and create class/id to it

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.



Solution 1:[1]

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>

Solution 2:[2]

you can add class :

tag.classList.add("gg");

and you can add class and id :

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

Solution 3:[3]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AwatITWork
Solution 2 fardin
Solution 3 Umesh Mahajan