Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery find within an array of elements

Tags:

jquery

I have selected a bunch of li elements that meet a certain criteria like so:

var x = $('li[attribute="value"]');

Now rather than searching the dom again, I want to search x for an li tag that has a specific id. I could use a .each to search x but was wondering if there was a one line statement I could use.

something like this:

var myLi = x.find("[id=23]");

or is it faster to search the dom using the id tag. What if I wanted to search on a second attribute?

Please advise.

Thanks!

Edit

Please note that I want to change the properties of myLi (say make its background color red) so I need a ref to the element. thanks.

like image 377
rkrauter Avatar asked May 25 '11 06:05

rkrauter


People also ask

How do you check if an array contains a value in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How do you find the value of an element in an array?

If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use indexOf() .

How do you iterate through an array in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How do you check if a value exists in an array JS?

The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.


1 Answers

You can do so:

var myLi = x.filter('#23');

jquery.filter(): Reduce the set of matched elements to those that match the selector or pass the function's test.

like image 131
Hck Avatar answered Oct 13 '22 18:10

Hck