Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get elements with one class but not another without iterating

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.

like image 211
mavrosxristoforos Avatar asked Oct 21 '13 11:10

mavrosxristoforos


2 Answers

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

like image 63
MackieeE Avatar answered Oct 31 '22 01:10

MackieeE


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

like image 23
Venu Avatar answered Oct 31 '22 01:10

Venu