Home > Software design >  using querySelectorAll after getElementById not working in javascript
using querySelectorAll after getElementById not working in javascript

Time:03-28

I have a lot of elements I color them with querySelectorAll Then I want to color one of the elements with getElementById Then I use querySelectorAll it again to color all the elements again ,The problem is the second time it does not work (the color is not changed with querySelectorAll).

There are other ways to do something like this getElementsByClassName But I want to work with the idea of the above method The code explains the question more:

<!DOCTYPE html>
<html>
<body>
<div >
<h2  id="myH1">This is an example h2</h2>
<h2  id="myH2">This is an example h2</h2>
<h2  id="myH3">This is an example h2</h2>
</div>
<button type="button" onclick="myFunction()">Set text color all</button>
<button type="button" onclick="myFunction2()">Set text color one</button>

<script>
function myFunction2() {
 var x = document.querySelectorAll(".main");
 var i; 
    for(i=0;i<x.length;i  )
      {
       x[i].style.color = "#00ff88"; 
      }
}

function myFunction() {
  document.getElementById("myH2").style.color = "#ff0000";
}
</script>

</body>
</html>

Please click on Set text color all first, then click on Set text color one the click on Set text color all again.

CodePudding user response:

Simply add the h2 also in the selector like:

var x = document.querySelectorAll(".main h2"); // add h2 here in the 

and then the color will be set on the "same" element's always and your CSS will work. The problem you are facing is (as Sebastian mentioned in the comment) that you set the color one time on the <div ... and another time on the <h2 id="myH2"...

<!DOCTYPE html>
<html>
<body>
<div >
<h2  id="myH1">This is an example h2</h2>
<h2  id="myH2">This is an example h2</h2>
<h2  id="myH3">This is an example h2</h2>
</div>
<button type="button" onclick="myFunction2()">Set text color all</button>
<button type="button" onclick="myFunction()">Set text color one</button>

<script>
function myFunction2() {
 var x = document.querySelectorAll(".main h2"); // add h2 here in the selector
 var i; 
    for(i=0;i<x.length;i  )
      {
       x[i].style.color = "#00ff88"; 
      }
}

function myFunction() {
  document.getElementById("myH2").style.color = "#ff0000";
}
</script>

</body>
</html>

  • Related