Flynn
Flynn

Reputation: 6211

Javascript: Select elements by ID

So I have an HTML list

<ul>
  <li id="item-foo"></li>
  <li id="item-bar"></li>
  <li id="zoop"></li>
</ul>

and in Javascript I want to get an array of the list items based on their ID. Basically, if the ID starts with item- then I want to get it in an array.

The first way I did this was just to loop through all the items in the DOM and take the ID as a string and match it that way. Is there a better way?

Upvotes: 0

Views: 375

Answers (4)

Tony Dinh
Tony Dinh

Reputation: 6726

Use selector: var some_array = $("li[id^='item-']") from here: http://api.jquery.com/attribute-starts-with-selector/

Upvotes: 1

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

As said in the other answers, jQuery selectors like [id^='item-'] will work fine, but it should be noted that this is not a jQuery-only feature, but rather a DOM selector, as specified by W3C.
In other words, if you don't feel like including a monolithic toolkit like jQuery, just so you can use some more special selectors, just write:

var itemIds = document.querySelectorAll("li[id^='item-']");

And you're there.
What's more, this will be faster than jQ. jQ can never match vanillaJS for speed. There's no need for you to use jQ here, so don't. JQ can make life easier, true, but not in this case. The selector is identical, so you don't need jQ.
All jQ will do here is slow you down, and help you write bad code... Sorry... I needed to get that off of my chest.

Upvotes: 3

arb
arb

Reputation: 7863

$("[id^='item-'"]

If you want to use jQuery, that selector should give you what you are looking for.

Upvotes: 0

Flash Thunder
Flash Thunder

Reputation: 12045

The proper selector in jQuery would be:

$('li[id^="item-"]')

Upvotes: 2

Related Questions