Reputation: 2413
lets say I wanted to search through divs with a certain class name.and if the divs dont have a certain id I want to add a class to them. ex.
<div id ="1" class="head"></div>
<div id ="2" class="head"></div>
<div id ="3" class="head"></div>
if(div.id != "1")
{
add class to all divs not = 1
}
how would this work thank you
Upvotes: 3
Views: 1304
Reputation: 490233
You can use this code to do that...
$('div.head:not(#1)').addClass('some-class');
For better performance, use...
$('div.head').not('#1').addClass('some-class');
For modern browsers...
[].slice.call(document.querySelectorAll('div.head')).filter(function(element) {
return element.id != 1;
}).forEach(function(element) {
element.classList.add('some-class');
});
You could drop the filter()
and use :not()
, like Zeta's answer.
For our lovable older IEs...
var divs = document.getElementsByTagName('div'),
divsLength = divs.length;
for (var i = 0; i < divsLength; i++) {
if (divs[i].id != '1' && ~divs[i].className.search(/\bhead\b/)) {
divs[i].className += ' some-class';
}
}
Depending on how far you need to support, you could always use document.getElementsByClassName()
so long as you know you will be required to filter div
elements if other elements may contain the same class name and you must have div
exclusively.
Additionally, an id
attribute can not start with a number, according to the spec.
Upvotes: 9
Reputation: 105886
var result = document.querySelectorAll('div.head:not(#validID)');
for(var i = 0; i < result.length; ++i)
result[i].className += ' yourClassName';
Demo. This won't require jQuery. If you prefer jQuery, see alex answer.
Upvotes: 1