Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Variable In Selector without string concatenation

I am writing a lot of code where I am using the same selectors but snippets of them for example

$('#menu > div.container a')

and

$('#menu span.highlight')

is there any method to have '#menu' in a variable and use that instead? The issue I have with string concatenation is that it requires one to be extremey disciplined about its use as even a single missing space will mess things up. What I would rather do is something like below:

var menuSelector = '#menu';
$('{menuSelector} > div.container a')
$('{menuSelector} span.highlight')

I have checked the documenation and such a feature does not exist. The problem with implementing such a feature is that jQuery needs to eval within the caller's context. Is this possible within javascript? Secondly how might I go about implementing this feature myself?

like image 361
Tahir Hassan Avatar asked Nov 23 '25 09:11

Tahir Hassan


1 Answers

use node caching so you evaluate nodes faster (you start search from a cached context)

$menu = $('#menu');

$menu.children('div.container a')
$menu.find('span.highlight');

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!