Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

795
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda