Reputation: 2857
Consider my element structure
<a href="#" class="close">X</a>
<div class="container">Lorem ipsum</div>
Now on click of the anchor tag I need to hide both the elements,
$('body').on('click', '.close', function(){
$(this).hide();
$('.container').hide();
});
How do I chain both the hide()
statements into one?
Upvotes: 2
Views: 77
Reputation: 317
You can use the following
$('body').on('click', '.close', function(){
$(".close, .container").hide();
});
Upvotes: 1
Reputation: 122026
No you cannot as the selectors are different. You can only chain if you are operating on same select element.
However, if you want to minimise the line you can consider grouping them instead of chaining using add().
$(this).add('.container').hide();
or
$('.container').add(this).hide();
Upvotes: 3
Reputation: 337743
You can use add()
to combine multiple selectors in to a single jQuery object:
$('body').on('click', '.close', function() {
$(this).add('.container').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<a href="#" class="close">X</a>
<div class="container">Lorem ipsum</div>
Upvotes: 6