1

It it possible to combine a variable and a html element in order to create a selector?

Say, I have this variable:

var element = $('.myElement');

Is it possible to reuse this variable instead of doing this:

$('.myElement input').val('');

Something like... (which obviously doesn't work)

$(element 'input').val('');

Thanks.

1
  • Straight forward no because element contain reference to $('.myElement') & when you use it inside it become $($('.myElement') 'input') so incorrect Commented Jan 21, 2014 at 9:04

3 Answers 3

5

you can do it by using the .find(),

element.find('input').val('');

Please read here to know more about .find()


As Mildly suggested, you could use the context feature of the selector too.

$('input', element)
Sign up to request clarification or add additional context in comments.

2 Comments

There is no need to rewrap the element. element.find()... will work.
Exactly, or by passing it as a context, $('input', element), which works just the same way.
2

You could use optional context for your selector like jQuery( selector [, context ] ).

For example:

var element = $('.myElement');
var child = $('input', element);

Docs

Comments

0

You can use:

$(element + 'input').val('');

For more information about selectors:

http://api.jquery.com/category/selectors/

The find() function is very helpful when the 'input' element is not always available or selecting more elements, that you can loop through each item:

$(element).find('input').each(function() { /*some code*/ } );

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.