Yuval Karmi
Yuval Karmi

Reputation: 26713

How to select a jQuery element's child with one selector?

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!

Upvotes: 3

Views: 7416

Answers (4)

user113716
user113716

Reputation: 322452

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.

Upvotes: 1

Robert Swisher
Robert Swisher

Reputation: 1300

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.

Upvotes: 0

Vaibhav Gupta
Vaibhav Gupta

Reputation: 1612

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

Upvotes: 1

ZippyV
ZippyV

Reputation: 13018

Almost there:

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

Upvotes: 8

Related Questions