I have multiple <p>
with the same class names, and only one has a child. I'm trying to only highlight the <p>
that has a child, but my code highlights all of them.
window.onload = function() { var highlight = document.getElementsByClassName('parent'); for (let i = 0; i < highlight.length; i++) { if (document.querySelectorAll(".parent.child").length > 0) { highlight[i].style.backgroundColor = "yellow"; } } }
<p class="parent"> Testing 1 </p> <p class="parent"> Testing 2 <span class="child"> test </span> </p> <p class="parent"> Test 3 </p> <p class="parent"> Testing 4 </p>
In recent browsers, you can do this with a single selector string - select .parent
s which have a child with :has(>.child)
.
for (const p of document.querySelectorAll('.parent:has(>.child)')) { p.style.backgroundColor = "yellow"; }
<p class="parent"> Testing 1 </p> <p class="parent"> Testing 2 <span class="child"> test </span> </p> <p class="parent"> Test 3 </p> <p class="parent"> Testing 4 </p>
Otherwise, going with your curent code, you'll have to reference the element being iterated over (the highlight[i]
), and call querySelector
on it to see if that one element has any matching children.
window.onload = function() { var highlight = document.getElementsByClassName('parent'); for (let i = 0; i < highlight.length; i++) { if (highlight[i].querySelector(".parent.child")) { highlight[i].style.backgroundColor = "yellow"; } } }
<p class="parent"> Testing 1 </p> <p class="parent"> Testing 2 <span class="child"> test </span> </p> <p class="parent"> Test 3 </p> <p class="parent"> Testing 4 </p>
I wouldn't use javascript for this just use the has selector
p:has(span) {
background-color:#f00!important
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.