2013-12-09 2 views
0

클래스 ".bar"가 포함되지 않은 클래스 ".foo"가있는 요소를 선택하고 클릭하려고합니다.jQuery 선택기로 getElementsByClassName을 사용할 수있는 방법 : not() selector

나는 다음과 같은 코드를 사용하고 싶습니다하지만 그것은 작동하지 않습니다 : 도움을

var inputs = document.getElementsByClassName('foo:not(bar)'); 
for(var i=0; i<inputs.length;i++) { 
    inputs[i].click(); 
} 

감사합니다!

var inputs = document.querySelectorAll('.foo:not(.bar)'); 

을 또는 당신이 당신의 태그 jquery을 가지고 :

+4

'.getElementsByClassName()'... 그것은 주목할 필요가 – Pointy

답변

5

당신은 querySelectorAll을 사용하려고 할 수 있습니다

$('.foo:not(.bar)').each(function() { 
    $(this).click(); 
}); 
+0

JQuery와 기능하지 않습니다 이것,'querySel ectorAll()'메소드는 인터넷 익스플로러와 하위 호환성이 없다. (매우 많은 것들은 ...) 9 개 미만이다. (나는 * 생각한다. 그러나 나는 완전히 확신 할 수 없다. . –

+0

@DavidThomas 어쨌든 jQuery 버전도 제공했습니다. jquery는 질문 태그입니다. OP가 jQuery를 사용하지 않았다면 그는 다른 솔루션을 요구할 필요가 있습니다. – antyrat

+0

완벽하게 작동하며 가장 좋은 답변으로 선택 하겠지만 너무 빨라서 아직 나를 허용하지 않을 것입니다! – YPCrumble

0

는 먼저 bar의없이 모든 foo의를 선택 .filter() 기능을 사용할 수 있습니다 :

JSFiddle

CSS

.foo, .bar{ 
    padding:20px; 
    font-weight:bold; 
} 

jQuery를

// get all foos and begine filtering 
$('.foo').filter(function(){ 

    // show what class each div has 
    $(this).text($(this).attr('class')); 

    // translates into: IF bar not exist then return this element 
    return !$(this).hasClass('bar'); 

// color the divs yellow 
}).css('background-color','yellow'); 

HTML

<div class='foo'></div> 
<div class='foo bar'></div> 
<div class='foo bar'></div> 
<div class='foo'></div> 
<div class='foo'></div> 
<div class='foo bar'></div> 
<div class='foo'></div> 
<div class='foo bar'></div>