KARAN GUPTA
KARAN GUPTA

Reputation: 71

not able to change the color of text on button click

on clicking the button the paragraphs are not getting colored, I'm not able to get the reason behind this.

<button onclick="changeBackGroundOfPs('#firstDiv');">Change backgrounds of p under a given element known by id</button>
  <br>
<div id="firstDiv">
  <p>First paragraph.</p>
  <p>Second paragraph.</p>
</div>
function changeBackGroundOfPs(id ) {
  var paragraphs = document.querySelectorAll(id   p);

  // Another way to iterate on all elements in a collection
 for (var i = 0; i < paragraphs.length; i++ ) {
   paragraphs[i].style.backgroundColor = "lightGreen";
  }
}

why this works without adding semicolons in query selector(document.querySelectorAll("#" + id + " p"));.

<button onclick="changeBackGroundOfPs('firstDiv');">Change backgrounds of p under a given element known by id</button>
  <br>
<div id="firstDiv">
  <p>First paragraph.</p>
  <p>Second paragraph.</p>
</div>
function changeBackGroundOfPs(id) {
  var paragraphs = document.querySelectorAll("#" + id + " p");

  // Another way to iterate on all elements in a collection
  for (var i = 0; i < paragraphs.length; i++ ) {
    paragraphs[i].style.backgroundColor = "lightGreen";
  }
}

Upvotes: 0

Views: 38

Answers (1)

Sifat Haque
Sifat Haque

Reputation: 6057

There is an issue in your querySelector Here is the right code

var paragraphs = document.querySelectorAll(`${id} p`);

Here is the working code.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button onclick="changeBackGroundOfPs('#firstDiv');">Change backgrounds of p under a given element known by id</button>
  <br>
<div id="firstDiv">
  <p>First paragraph.</p>
  <p>Second paragraph.</p>
</div>
  
  
  <script>
    console.clear();

    function changeBackGroundOfPs(id ) {

      var paragraphs = document.querySelectorAll(`${id} p`);

      // Another way to iterate on all elements in a collection
      for (var i = 0; i < paragraphs.length; i++ ) {
        paragraphs[i].style.backgroundColor = "lightGreen";
      }
    }
    
  
  </script>
</body>
</html>

Upvotes: 1

Related Questions