Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: If all children have same class

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... :-/

like image 485
curly_brackets Avatar asked Sep 22 '11 10:09

curly_brackets


People also ask

How to find all children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How to find child specific class in jQuery?

children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements. Here selector is the selected element whose children are going to be found.

How do you select all elements with the class of Apple in jQuery?

var somevar = "apple" $( .... select all elements with class == somevar ).


1 Answers

$("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.

like image 92
Ariel Avatar answered Sep 27 '22 19:09

Ariel