1

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?

4 Answers 4

4

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();
Sign up to request clarification or add additional context in comments.

Comments

2
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.

5 Comments

Would that be $('a.collapse', $tbody).hide(); ?
Not sure who you want to answer. This seems to be the best choice as it is a direct select instead of .find(). Thank you!!!
Is there a difference between using $tbody as the second parameter or using $tbody.find('a.collapse'); ?
Thank you all. It's not often I get a full and complete answer. Happy Holidays!!!
1

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();

1 Comment

From what I've read about selectors, isn't it better to use direct select instead of .find()?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.