Blog Seperator
May 17th, 2010

Simple jQuery Tool Uncovered

It’s no secret we love jQuery here at lifeBLUE. It’s made our life easier and our applications better. One task I find myself frequently doing is finding something nested within the tag or element I’m working with. For example.

<div id="iKnowAboutThis" >
    <div class="one" >One</div>
    <div class="two" >Two</div>
    <div class="iWantThis" >Three</div>
</div>

I know all about the div element with the id of “iKnowAboutThis”. I can get at that with a simple:

var iGotIt = $("#iKnowAboutThis");

I can use the jQuery object to do whatever I want. But what if I need to get at the element with the class “iWantThis” that is nested within “iKnowAboutThis”. If I have more than one on the page then I can’t just do this:

var iGotThis = $(".iWantThis");

If I do the above, I’ll get all of the elements with that class. All I want is the one nested within “iKnowAboutThis”. Fortunately, jQuery has a very powerful tool to help me.

By using the context option within the jQuery selector I am able to get at any nested item I want like this.

var iGotIt = $("#iKnowAboutThis");
var iWantThis = $(".iWantThis", iGotIt);

With that little snippet, my search for elements with the selector I specify stays within the context I set for it.

There you go, simple!

Author: JMills
May 17th, 2010 in Nerd Matrix, Web Development | Trackback
Blog Seperator
Share this!
Post a Comment
Name:
Email Address:
URL:
Comments: