Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element by id from existing jQuery object

Tags:

jquery

Ok this has got to be a stupid simple one, but I just can't find the documentation

  <ul>
      <li class="foo" id="jack"  ></li>
      <li class="foo" id="jill"  ></li>
      <li class="foo" id="tom"   ></li>
      <li class="foo" id="dick"  ></li>
      <li class="foo" id="harry" ></li>
  </ul>

And the simple jQuery

 var listItems = $('li.foo');

now how do I get #jack from listItems ? I already know .eq() .get() .find() ect. but not one that will work in one move. Not based on index, not looking for a child or parent, but based on the id of existing elements selected. Anyone know this one?

like image 439
Fresheyeball Avatar asked Mar 12 '26 23:03

Fresheyeball


2 Answers

Whenever you're dealing with an id there is no need to do a sub-query. An ID is unique and can just be queried directly

$('#jack')

If you did want to do a sub-query though for a non-ID value then look to filter

$('ul li').filter('.foo')
like image 105
JaredPar Avatar answered Mar 15 '26 00:03

JaredPar


Use .filter() like so:

listItems.filter('#jack');
like image 26
Anthony Grist Avatar answered Mar 14 '26 23:03

Anthony Grist