2011-09-22 48 views
4

如何檢查所有孩子或所有選擇器是否具有相同的類?jQuery:如果所有孩子都具有相同的類

類是未知...

<script> 
    $(document).ready(function() { 
     var symbols = $("div:first-child").attr("class"); 

     if ($("div").hasClass(symbols).length == 3) { 
      console.log("same"); 
     }; 
    }); 
</script> 
<div class="john"></div> 
<div class="john"></div> 
<div class="john"></div> 

這不工作...: -/

回答

12
$("div").not('.john').length 

如果有任何的div都不類約翰這樣會找到他們,那麼你檢查長度,如果它不是零,那麼一些存在。

這是一個問題:

$("div:first-child").attr("class") 

它會返回整個類的字符串,但DIV可以有多個類,和所有將被退回。但是,當你檢查我的代碼或hasClass時,你只能發送一個班級,而不是一堆。

+0

非常優雅的答案。 –

3

HTML: <div class="parent"> <div class="child"></div><div class="child"></div><div class="child"></div></div>

的Jquery:

if ($(".parent").children().length == $(".parent").children(".child").length) { 
    alert("wooo all the things have teh same class"); 
} 
+0

這個類是可變的......我不知道這個類...... –

+0

只需製作一個像.children(「。」+ className)而不是「.child」的字符串;) –

相關問題