最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: If all children have same class - Stack Overflow

programmeradmin1浏览0评论

How do I check if all children, or all selectors, have same class?

The class is unknown...

<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>

This doesn't work... :-/

How do I check if all children, or all selectors, have same class?

The class is unknown...

<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>

This doesn't work... :-/

Share Improve this question edited Sep 22, 2011 at 10:11 curly_brackets asked Sep 22, 2011 at 10:04 curly_bracketscurly_brackets 5,59815 gold badges61 silver badges103 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14
$("div").not('.john').length

If any of the divs are not class john this will find them, then you check the length and if it's not zero then some exist.

This is a problem:

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

It will return the entire class string, but the div could have more than one class, and all will be returned. But when you check with either my code or hasClass you can only send in one class, not a bunch together.

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)

  1. 暂无评论