Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report

0

you can add class :

tag.classList.add("gg");

and you can add class and id :

tag.setAttribute("id", "ff");
tag.setAttribute("class", "bb");
about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!