Get elements with one class but not another without iterating
Asked Answered
C

2

10

In the following simple HTML, I would like to get all elements with class1 but not with class2.

<li class="class1 class2"></li>
<li class="class1 class3"></li>
<li class="class1 class4"></li>

By using getElementsByClassName('class1') we could get all elements and then possibly remove elements by checking if a certain class exists.

Is there a better way to do this, without iterating?

I found this interesting post about getting elements with multiple classes, so dare I ask: Is there something like this: document.getElementsByClassName("class1 !class2")?

P.S.: I don't want to use jQuery.

Cucurbit answered 21/10, 2013 at 11:0 Comment(0)
P
23

If you don't mind using the increasingly compatible .querySelectorAll() it's possible with just:

  var getClassOne = document.querySelectorAll( '.class1:not(.class2)' );

Fiddle: http://jsfiddle.net/5tSGv/52/

Although without it, you'd have to iterate the className somehow

Polder answered 21/10, 2013 at 11:4 Comment(3)
Thank you MackieeE, but the question is "Is there a better way to do this?", other than what you posted (which I described in my question)Cucurbit
I see! Apologies for skimming over the question too quickly - Added a fiddle with querySelectorAll().Polder
Thanks MackieeE. I don't mind using it at all. I would love to see more suggestions, though, but if they don't come up, I will accept your answer.Cucurbit
H
3

querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

So if the page is not having a dynamic generating div's, you can use querySelectorAll().

Histochemistry answered 23/8, 2020 at 18:6 Comment(1)
Thanks! That's a useful hint.Cucurbit

© 2022 - 2024 — McMap. All rights reserved.