Home > Software engineering >  I am getting only first header element style color as green, why?
I am getting only first header element style color as green, why?

Time:06-16

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>

CodePudding user response:

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).

CodePudding user response:

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

  • Related