是否可以选择元素First
但不是 Second
?
<p> <code>first</code> </p>
<p> Text <code>second</code> Text </p>
我打算选择 <code>
当它是 <p>
的 child 时但在 <p>
中没有内容(空格除外)
我想在没有 JS 的情况下完成它,如果不可能的话,如果它的解释也是一个答案
最佳答案
您可以使用 jQuery 中的过滤器来做到这一点:
$('p').filter(function() {
var nodetoCheck = $(this).contents()[0];
if ($(this).contents()[0].nodeValue.trim() === '') {
nodetoCheck = $(this).contents()[1];
}
if (nodetoCheck.nodeType === 1) {
return true;
}
}).addClass('selected');
JSfiddle 示例:https://jsfiddle.net/jennifergoncalves/eywk7b53/1/
关于CSS选择非常直接的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44627790/