9

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.

2
  • if you provide fiddle, then it's easy to solve your problem Commented May 25, 2011 at 7:02
  • I'd say, go the easy way first (searching the DOM for the ID) and see if it has any impact. Do some profiling if you want to. If you search for another attribute, then yes, filtering the current list is better. Commented May 25, 2011 at 8:45

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The following are the various ways in which you can get the element starting from the fastest

Profiled result

  1. The ID selector
  2. .filter()
  3. .find()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.