The Light
The Light

Reputation: 27021

How to Find an Element by Attribute in JQuery?

I have a variable containing the list of selects, then I'd need to filter and find only those that has dependsOn attribute with the value of 'EventType'.

I tried the below but it doesn't find the select and returns 0:

var selects = $("select");
var count = selects.find("[dependsOn='EventType']").length
alert(count);

I wrote the below which works but isn't there an easier way?

var dependents = [];
        selectLists.each(function() {

            var dep = $(this).attr('dependsOn');
            if (dep === undefined) return;

            dependents.push(dep.val());
        });

Upvotes: 0

Views: 72

Answers (4)

Felix
Felix

Reputation: 38112

If you use data attribute

then you can do:

var selects = $("select");
selects.find('[data-dependsOn="EventType"]').length;
alert(count);

find() is used to select the child elements, if you want to target select element, you can use:

var selects = $('select[data-dependsOn="EventType"]').length;
alert(count);

Upvotes: 0

Quentin
Quentin

Reputation: 944320

See the documentation for find:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

You want to use filter:

Reduce the set of matched elements to those that match the selector or pass the function's test.

selects.filter("[dependsOn='EventType']").length

Alternatively, just put the condition in your initial selector:

$("select[dependsOn='EventType']").length;

Upvotes: 3

MRodriguez08
MRodriguez08

Reputation: 191

try with you'r browser's console (I'm using chrome) and use this:

selects = $("select[dependsOn='EventType']");

It worked just fine for me. Hope it helps!!

Upvotes: 0

tymeJV
tymeJV

Reputation: 104795

If that attribute is on the actual select tag, just do:

var selects = $("select[dependsOn='EventType']"); 

Although, dependsOn doesn't seem like a valid attribute. Check out custom data-* attributes to have completely valid HTML.

Upvotes: 5

Related Questions