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

794
Views
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 answers
Answer question

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 Report

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 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!