Reputation: 631
How can I directly select classes, etc using a variable?
var $tbody = $(".tbl-locations-body");
$(".tbl-locations-body a.collapse").hide();
$(".tbl-locations-body tr.child-row").hide();
$(".tbl-locations-body .container").first().hide();
$(".tbl-locations-body .tab-content").hide();
I want to use $tbody
to perform the methods. What is the syntax?
Upvotes: 1
Views: 150
Reputation: 631
I've been reading up on this and although
var $tbody = $(".tbl-locations-body");
$("a.collapse", $tbody).hide();
looks cleaner, under the hood it's changed to $tbody.find() anyway. So the better answer is to use the find method to start with - and as Rory pointed out, you can select multiple too.
Upvotes: 0
Reputation: 1085
var $tbody = $(".tbl-locations-body");
$("a.collapse", $tbody).hide();
// etc...
Explanation:
If you pass $tbody as second parameter into jquery function, you will search only in a scope of that element($tbody), rather than in whole document.
Upvotes: 2
Reputation: 42352
You can use the find()
method - see code below:
var $tbody = $(".tbl-locations-body");
$tbody.find("a.collapse").hide();
$tbody.find("tr.child-row").hide();
$tbody.find(".container").first().hide();
$tbody.find(".tab-content").hide();
Upvotes: 1
Reputation: 337560
You could use the find()
method from the $tbody
jQuery object. Note that you can apply multiple selectors as well to make the calls a one-liner:
var $tbody = $(".tbl-locations-body");
$tbody.find('a.collapse, tr.child-row, .container:first, .tab-content').hide();
Upvotes: 4