Royi Namir
Royi Namir

Reputation: 148704

Search for immediate selector in jQuery?

I have this function which accepts obj (Jq object) as a parameter

However , in this function , I only need obj which is :not(:disabled) and :not([readonly]

currently I've managed to do it with :

function CheckRequiredSelection(obj)
{
    obj.find(".requiredSelection:visible:not(:disabled):not([readonly])").andSelf().each(function ()
    {
...
    });

}

But I really want to get rid of find and addSelf trick.

Any help ?

The document can contain :

Edit #1 ...

<select class="requiredSelection">
...
</select>

<select class="requiredSelection">
...
</select>

and before submit : I do something like :

CheckRequiredSelection($(".requiredSelection"))

Edit #2

I could have check inside the .each loop but then it wont be efficient since it's after the selector. ( instead of getting 5 filtered elements from 100 , I will get 100 elements and THEN i'll have to filter. That's not nice).

Upvotes: 0

Views: 60

Answers (2)

Jashwant
Jashwant

Reputation: 29025

You are looking for is

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

So, your code will look like,

function CheckRequiredSelection(obj) {
    obj.is(".requiredSelection:visible:not(:disabled):not([readonly])")
}

I am not sure if its faster than filter or not.

But is is there to be used in such situations.

You can test the performance at jsperf

Upvotes: 0

pktangyue
pktangyue

Reputation: 8534

I think you want .filter().

function CheckRequiredSelection(obj)
{
    obj.filter(":visible:not(:disabled):not([readonly])").each(function ()
    {
...
    });

}

Upvotes: 2

Related Questions