9

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.

Community
  • 1
  • 1
mavrosxristoforos
  • 3,573
  • 2
  • 25
  • 40

2 Answers2

22

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

MackieeE
  • 11,751
  • 4
  • 39
  • 56
  • 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) – mavrosxristoforos Oct 21 '13 at 11:08
  • I see! Apologies for skimming over the question too quickly - Added a fiddle with `querySelectorAll()`. – MackieeE Oct 21 '13 at 11:15
  • 1
    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. – mavrosxristoforos Oct 21 '13 at 11:49
2

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().

Venu
  • 1,513
  • 3
  • 19
  • 37