[英]Add styling only to elements with a child
I have multiple <p>
with the same class names, and only one has a child.我有多个
<p>
具有相同的 class 名称,只有一个有孩子。 I'm trying to only highlight the <p>
that has a child, but my code highlights all of them.我试图只突出显示有子项的
<p>
,但我的代码突出显示了所有这些。
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)
.在最近的浏览器中,您可以使用单个选择器字符串 - select
.parent
来完成此操作,其中有一个孩子: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.否则,使用您当前的代码,您必须引用被迭代的元素(
highlight[i]
),并对其调用querySelector
以查看该元素是否有任何匹配的子元素。
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我不会为此使用 javascript 只需使用 has 选择器
p:has(span) {
background-color:#f00!important
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.