Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

277
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda