Solution 1 :

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>

Problem :

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";
  }
}

Comments

Comment posted by palaѕн

Could you please explain what does

Comment posted by KARAN GUPTA

it should select all paragraphs within div

Comment posted by KARAN GUPTA

i got it i need to enclose them in id p in ‘ ‘

Comment posted by palaѕн

Before posting the code at least test it once and check console for errors.

Comment posted by KARAN GUPTA

I’m not yet fully acquainted with the use of console for checking errors, thanks for the suggestion

By