Testy
Testy

Reputation: 301

Select all element with particular class with jQuery

What is the best way for me to select find() all the elements that have a .btn-success class into and only in my #step_3 <div> ?

<div class="row justify-content-center" id="step_3">
    <div class="col-lg-12">
        <div class="row row-grid mt-4">
            <div class="col-lg-4 col-md-6">
                <div class="card shadow border-0">
                    <div class="card-head">
                        ...
                    </div>
                    <div class="card-body selected">
                        <h6 class="text-primary text-uppercase">Appartement #6</h6>
                        <div class="card-profile-stats justify-content-center">
                            <div class="row mb-4 p-0 m-0">
                                ...
                            </div>
                        </div>
                        <a href="#" data-action="book-room" data-roomid="2" class="btn mt-0 btn-success"><i class="fa fa-check"></i> Désélectionner</a>
                    </div>
                </div>
            </div>
        </div>
        <button class="btn btn-lg btn-primary" type="button" data-validate="step_3">Valider</button>
    </div>
</div>

What I try is:

$('[data-validate="step_3"]').on('click', function (e) {
   e.preventDefault();

   var $elements = $(this).find('.btn-success');
   console.log($elements);
});

But it doesn't work because each time it return me 0 element.

Thanks for your help.

Upvotes: 1

Views: 174

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115282

Get the common parent which is #step_3(or get .row using closest() method) and then get the element using find() method or get by using Descendant selector.

$('[data-validate="step_3"]').on('click', function (e) { e.preventDefault();
   var $elements = $('#step_3 .btn-success');
   // or $('#step_3').find('.btn-success');
   // or $(this).closest('.row').find('.btn-success');
   console.log($elements.length);
});

Upvotes: 1

Related Questions