javascript - how to search through only div with a certain class name on a page - Stack Overflow

admin2025-04-20  0

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

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

Share Improve this question asked Feb 14, 2012 at 23:19 waa1990waa1990 2,4139 gold badges28 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

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.

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.

$('div.head[id!="1"]').addClass('myClass');
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745149499a287536.html

最新回复(0)