views:

51

answers:

4

I have an div with the id article_50. If I were to select the .title element inside article_50, I could do the following: $("#article_50 .title").

Now say I want to select that same title, but within a click event:

$("#article_50").click(function(){
    $(this).children(".title").hide();
});

Now I had to call the children method to select that .title element. Could I select it within the same selector without the need to call children?

Something like this:

$("this .title").hide();

Thanks!

+5  A: 

Almost there:

$(".title", this).hide();
ZippyV
+1 for the correct answer, but I think it is less "readable" than $(this).children(".title").hide();
mathieu
+1  A: 
$("#article_50").click(function(){ $(".title", this).hide(); });
Vaibhav Gupta
A: 

Shouldn't you just be able to say:

$("#article_50").click(function(){ $("#article_50 .title").hide(); });

That's nearly the same and you don't need to call children.

Swish
absolutely, but if instead of a specific ID i had a class, and several elements of that class in the page, i'd be forced to use `this` to identify it. good point, though!
yuval
A: 

Use .children() if the .title element is actually a child of this.

When you do:

$(".title", this).hide();

...jQuery has to run 7 or 8 tests before it figures out that you're looking for .title inside of this.

Then jQuery just flips it around into this:

$(this).find('.title')

...and starts over. So it is calling a method anyway after all that testing. As you can see it is not very efficient.

Also, because .children() only looks one level deep, it is faster to use .children() than .find() if your element is actually a child.


EDIT:

An even faster way would be to cache the #article_50 element in a variable, so you don't need to create a jQuery object for $(this) every time you click.

var $art_50 = $("#article_50").click(function(){
    $art_50.children(".title").hide();
});

// Now you have a variable that you can use outside the click handler as well
//   in case you are selecting it elsewhere in your code.
patrick dw