简体   繁体   English

用于跳过元素的查询选择器

[英]querySelector for skipping elements

I have a question about the querySelector.我有一个关于 querySelector 的问题。 is there a way to search for all p elements in an html file but skip those p elements who are in a specific div?有没有办法在 html 文件中搜索所有 p 元素,但跳过特定 div 中的那些 p 元素?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 <div>
     <p>hit</p>
     <p>hit</p>
     <p>hit</p>
     <div>
         <p>hit</p>
         <p>hit</p>
         <p>hit</p>
         <p>hit</p>

     </div>
 </div>
<div class="donthit">
    <p>dont</p>
    <p>find</p>
    <p>us</p>
</div>
</body>
</html>

thats my example html.这就是我的示例 html。 is there a way to get all p elements but not the ones in div class = "donthit"?有没有办法获得所有 p 元素而不是 div class = "donthit" 中的那些?

You can first get all the divs without the specific one then find the p element inside:您可以先获取所有没有特定的 div,然后找到里面的p元素:

 $('div:not(.donthit)').children('p').addClass('red');
 .red { border:1px solid red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <p>hit</p> <p>hit</p> <p>hit</p> <div> <p>hit</p> <p>hit</p> <p>hit</p> <p>hit</p> </div> </div> <div class="donthit"> <p>dont</p> <p>find</p> <p>us</p> </div>

You can use the .not() method or :not() selector您可以使用 .not() 方法或 :not() 选择器

Code based on your example:基于您的示例的代码:

$("div:not(.donthit)").children("p")   // not selector 
$("div").not(".donthit").children("p") // not method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM