tags:

views:

479

answers:

3

When using the 'this' keyword in jQuery, what is the syntax for adding basic filters.

For example:

$(this):contains('foo')

$(this):visible OR $(this:visible)
A: 

use this syntax: jQuery( expression, [context] )

$(":contains(foo)", this)
$(":visible", this)
$("any-selector", this)
duckyflip
that's not correct. It will only select sub-elements of 'this'
Philippe Leybaert
the jQuery( expression, context ) is the same as jQuery(context).find(expression).
Lathan
+1  A: 

That's what the filter() method is for:

$(this).filter(":contains(foo)");
$(this).filter(":visible")

According to the docs:

Removes all elements from the set of matched elements that do not match the specified expression(s).

Philippe Leybaert
Yes, that will filter your matched elements by your selector, but our matched elements = [this]. You've only selected "this". So if this doesn't match your selector you would have to do a .size() to tell if it matched or not... find looks inside the selected elements, and is returns a logical true / false responce of the selector on the set.
Lathan
+2  A: 

For Searching for items within this:

$(':visible, any-selector', this)
$(this).find(':visible, any-selector')

if you want a true or false return:

if($(this).is(':visible, any-selector')){
    alert('this is visible, or matches "any-selector");
    }
else{
    alert('this is hidden, or doesn't match "any-selector");
    }
Lathan