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!
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.
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.
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() .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With