最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - querySelectorAll and .not() - Stack Overflow

programmeradmin1浏览0评论
<div class="alpha">
   <div class="beta">
      <label style="color:red; font-size: 12px;">Hello</label>
   </div>
</div>

I want to exclude (= not include), the above label. This includes it (tested successfully):

document.querySelectorAll(.alpha .beta label");

Now how to exclude it? I want to select all my label class but this one I want to exclude only has a label style .

<div class="alpha">
   <div class="beta">
      <label style="color:red; font-size: 12px;">Hello</label>
   </div>
</div>

I want to exclude (= not include), the above label. This includes it (tested successfully):

document.querySelectorAll(.alpha .beta label");

Now how to exclude it? I want to select all my label class but this one I want to exclude only has a label style .

Share edited Sep 15, 2018 at 20:50 paros asked Sep 15, 2018 at 20:14 parosparos 191 silver badge5 bronze badges 12
  • 1 document.querySelectorAll("div:not(.alpha .beta label)"); this makes no sense, cause you are saying "Select div, but not label". Label is not a div to begin with, – azrahel Commented Sep 15, 2018 at 20:19
  • Which elements do you want to include? – Bergi Commented Sep 15, 2018 at 20:20
  • You cannot have a plex selector (i.e. a "path" over multiple levels) as the argument to :not() – Bergi Commented Sep 15, 2018 at 20:25
  • 1 Unfortunately there is no css parent selector. Seems like you want label whose parents do not contain .beta, .alpha in that order. – Salman Arshad Commented Sep 15, 2018 at 20:30
  • 1 @paros If i'm understanding correctly, you could do document.querySelectorAll("label[class]") - this only selects labels that have a class attribute. Example – Tyler Roper Commented Sep 15, 2018 at 21:05
 |  Show 7 more ments

2 Answers 2

Reset to default 3

You cannot use CSS selectors to match "all labels except the one contained in div.alpha div.beta". However, you gave an alternative definition of your expected results:

I want to select all my <label class=…> but this one I want to exclude only has a <label style=…>.

You can do that using an attribute selector:

document.querySelectorAll("label[class]:not([style])")

Try this:

document.querySelectorAll("*:not(.div_label):not(.alpha):not(.beta)");

You don't need that last 'label' part, as label is not a div (and you are asking for div to get selected, right?), so it wont get selected anyway

发布评论

评论列表(0)

  1. 暂无评论