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.
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
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With