top
middle

Is it possible to combine a variable and a selector in jQuery?

Say I have this HTML code:

<div class="top">top <div class="middle">middle <div class="bottom">bottom</div> middle</div> top</div> <div class="middle">outside middle</div> 

Is there a way to create a variable for a selector and then use it as part of another selector? This is what I am trying to do, but it does not work:

 $top = $('.top'); $($top + ' .middle').click(function(){ $(this).toggleClass('green'); }); 

I am sure that I do not need to reselect .top, as the variable did, so I'm sure I need to do something with $ top, I'm just not sure what.

http://jsfiddle.net/ftXLx/1/

+4
source share
3 answers

Using

 $('.middle', $top) 

or

 $top.find('.middle') 

You could also just combine selectors that are strings with

 $($top.selector + ' .middle') 

but it will only be slower and less readable ...

+14
source

You can use find()

Description: Gets the children of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

 $top.find(".middle"); 
+3
source

You can simply select it like this:

 $('.top .middle').click(); 
0
source

Source: https://habr.com/ru/post/1484235/


All Articles