Kuro
Kuro

Reputation: 868

How to combine "this" with another selector?

I'm trying to write a selector, that gets this object only in case it is an anchor. I want it to get nothing in case it is anything but <a> tag.

$('.link').mouseover(function(){

    $("a", this).css('color','#00F');

})

the $("a", this).css('color','#00F'); doesnt work, but has desired effect if i leave only this in query. all the other selectors i could find in examples, blogs, and documentation were for getting children objects ( find() children()), combining two selectors(with add()), or pretty much anything else but the thing I'm looking for. can anyone help, please?

Upvotes: 1

Views: 1515

Answers (1)

Matt
Matt

Reputation: 75317

You can either use the is() method to check whether $(this).is('a'), and then react accordingly;

if ($(this).is('a')) {
    $(this).css('color', '#00F');
}

But perhaps a better solution in this situation is to use the filter() method to $(this).filter('a').css('color','#00F');

To note, filter() filters the current jQuery object; so $('*').filter('a') would filter the as out of allll the elements. $('a', this) on the other hand (equivalent to $(this).find('a')) searches descendants of elements in the jQuery object which match the provided selector.

Upvotes: 5

Related Questions