1 回答
TA贡献1883条经验 获得超3个赞
您的代码中存在问题,这是正确的代码querySelector
var paragraphs = document.querySelectorAll(`${id} p`);
下面是工作代码。
<!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>
添加回答
举报