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

802
Vistas
I am getting only first header element style color as green, why?

Here out of all 4 header element I am getting only first header element to be printed as green

for (let i = 1; i <= 4; i++) {
  var tag = document.createElement("h1");
  var text = document.createTextNode(i + " Tutorix is the best e-learning platform");
  tag.appendChild(text);
  var element = document.getElementById("new");
  element.appendChild(tag);
  let h1 = document.querySelector("h1");
  h1.setAttribute("style", "color: green;");
  // console.log("Hi there"+h1);
}
<div id="new">

</div>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I am getting only first header element style color as green, why?

Because document.querySelector only selects the first element that matches.

If you want to set the color of the element you just added, use the reference you already have to the element: tag. (Side note: tag is an odd name for that variable, because it doesn't contain or refer to a tag, it refers to an element.)

for (let i = 1; i <= 4; i++) {
  var tag = document.createElement("h1");
  var text = document.createTextNode(i + " Tutorix is the best e-learning platform");
  tag.appendChild(text);
  var element = document.getElementById("new");
  element.appendChild(tag);
  tag.setAttribute("style", "color: green;");
}
<div id="new">

</div>


Side note: In general, it's cleaner to assign to properties on the style object rather than setting the style attribute:

tag.style.color = "green";

They do different things (the above only sets the color to green without changing anything else; setting the style attribute completely replaces all inline styles for the element with what you provide).

about 4 years ago · Juan Pablo Isaza Denunciar

0

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned. Query Selector

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors. querySelectorAll

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