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

lets say I wanted to search through divs with a certain class name.and if the divs dont have a certain

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745149498a4613802.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信