Wednesday, October 6, 2010

Using this together with other selectors on jQuery.



I'm not sure if anyone else has stumbled upon this proble, but it took me a while to find about this, even thought it was in front of me the whole time.

While doing Events for many tags at a time, or performing a $().each, sometimes, i wanted to act on children from from the specific selector i was on, i was looking for a way to use "this" along with other selectors, but recently i found out the easiest way to do it. 

Lets say we have the following code used for the Following Situation.

<div class="outer" id="first"> Click me <div class="inner"> Div 1 </div></div>
<div class="outer" id="second"> Or me <div class="inner"> Div 2 </div></div>
<div class="outer" id="third"> Or me <div class="inner"> Div 3 </div></div>

<script type="text/javascript">
$(".outer").live("click", function() {
$(".inner", this).css("background-color", "#aaaaaa");
});
</script>

What was done above, was using the context parameter for jQuery to select an element inside the element we refer to with "this". When adding  "this" as the context, it will only look for the elements with class "inner" that are inside the element that triggered the action.


Context may also contain other selector, for example, if we use $(".inner", "#second").hide();
we will only be hiding the element with the "inner" class that is a child of the element with the id "second".


Now Let's try it!...

Click me
Div 1
Or me
Div 2
Or me
Div 3

I hope this was Helpful. Any doubts, questions, suggestions or curses, please let me now!!.

No comments:

Post a Comment