tags:

views:

105

answers:

2

Hi,

I want to find an element by class name. I know it will appear in a particular parent div, so rather than search the entire dom, I'd like to search only the particular div. I am trying this, but does not seem to be the correct syntax:

var element = $("#parentDiv").(".myClassNameOfInterest");

what's the right way to do that?

Thanks

+1  A: 
var element = $("#parentDiv .myClassNameOfInterest")
Jared I
@Jared - I think this may actually be slower. I don't think this reduces the context of the search to the `#parentDiv`. I'm pretty sure it is still searching the DOM for the class, then when it finds one, it checks to see if it is a descendant of `#parentDiv`.
patrick dw
@patrick, you are correct. As in your example, specifying the optional context parameter with an id selector offers the best performance... `$(".myClassNameOfInterest", "#parentDiv");`
Steve Wortham
+5  A: 

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest");

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv");

...which sets the context of the jQuery object to the #parentDiv.

EDIT:

Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

patrick dw
The second method is actually converted to the first method by jQuery behind the scenes. The first method is the endorsed way to do it. You're also correct regarding the div - adding that tells jQuery to only check divs for the classname, instead of all elements.
Mike Robinson
@Mike - I heard that the other day about jQuery converting the 2nd example to the 1st, so I took a quick look at the source. Sure seemed to. Thanks for the confirmation. :o)
patrick dw