2

I have the following:

$(function(){
   $table = $('#print_types table');
});

Is it possible to do something like this:

$(function(){
   $($table + ' tr:last > td:first').after('something');
});

Since I'm caching a table element, how can I manipulate the table like I showed above? Normally I would have written it like this:

$(function(){
   $('div#print_types table tr:last > td:first').after('something');
});

The problem is I have a bunch of these statements and is the reason why I cached the table. I tried doing what I did, but I get an error. Am I missing something here?

3 Answers 3

2

Just use .find:

$table.find('tr:last > td:first')

This is essentially equivalent. You can't use $($table +... because $table's toString is not the selector you want.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right, I didn't think of using .find(). But it works now. I knew there was something off when I was writing $($table +... Thanks!
0

$table is a jQuery object. A jQuery selector is a string and you can not concatenate a string and an object.

Use find() instead

 $table.find(' tr:last > td:first').after('something');

Comments

0

What you are looking for is context

$table = $('#print_types table');

$('tr:last > td:first', $table).after('something');

This is basically the same as

$table.find('tr:last > td:first').after('something');

.find()

6 Comments

personally find() is easier to read IMO... internally jQuery uses find() when context provided so no performance benefits either
@charlietfl I agree. I am just laying the options out for the OP.
@charlietfl context is useful when you don't have a jQuery object at your disposal, e.g. $('selector', this) vs. $(this).find('selector')
@charlietfl I know it's not the case here, I was just pointing it out. Yes, $(this) is not expensive; I'm just saying that they are not necessarily equivalent.
@ExplosionPills with exception of an extra $(this) call they are essentially the same.. core will use find() internally for context and likely has to wrap it in $(context)
|

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.