Lynx
Lynx

Reputation: 1482

How to only select one multiple class with jQuery

I have a form that has checkmarks behind them. They all are tied to labels and have all the some class names. I could just make new classes or ID's for each one but figured their was an easier way to only select the checkmark that is inside that particular class?

http://jsfiddle.net/70fbLooL/

 <script>
    $(document).ready(function(){
        $(".companyLabel").click(function(){
          $(".fa-check").toggle();
          $(this).toggleClass("companyLabelBackground");
        });
    });
</script>

Upvotes: 0

Views: 63

Answers (2)

Farshad
Farshad

Reputation: 1485

you can use .closest() and .find() to dynamically detect closest div or element. for example

$(this).closest('.companyLabel').find('.fa-check').toggle();

code :

$(document).ready(function(){
            $(".companyLabel").click(function(){
                 $(this).closest('.companyLabel').find('.fa-check').toggle();
            });
        });

JSFIDDLE DEMO

Upvotes: 0

imbondbaby
imbondbaby

Reputation: 6411

$(".fa-check").toggle(); will toggle all elements with class .fa-check.

Instead, use find() to get the closest element in relation to this.

Try this:

$(document).ready(function () {
    $(".companyLabel").click(function () {
        $(this).find(".fa-check").toggle();
        $(this).toggleClass("companyLabelBackground");
    });
});

JSFiddle Demo

Upvotes: 2

Related Questions