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>
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";
}
}
Before posting the code at least test it once and check console for errors.
I’m not yet fully acquainted with the use of console for checking errors, thanks for the suggestion