waa1990
waa1990

Reputation: 2413

how to search through only div with a certain class name on a page

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

Answers (3)

alex
alex

Reputation: 490233

jQuery

You can use this code to do that...

$('div.head:not(#1)').addClass('some-class');

jsFiddle.

For better performance, use...

$('div.head').not('#1').addClass('some-class');

jsFiddle.


Without jQuery

For modern browsers...

[].slice.call(document.querySelectorAll('div.head')).filter(function(element) {
    return element.id != 1;
}).forEach(function(element) {
    element.classList.add('some-class');
});

jsFiddle.

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';    
    }
}

jsFiddle.

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

Zeta
Zeta

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

HellaMad
HellaMad

Reputation: 5374

$('div.head[id!="1"]').addClass('myClass');

Upvotes: 0

Related Questions