56

I have a structure of html like this:

<div id="triger1">some elements inside</div>
<div id="triger2">some elements inside</div>
<div id="triger3">some elements inside</div>
<div id="triger4">some elements inside</div>

How do I get array of all the div's in JQuery with the triger ID in them (as you can see, they all have triger but different numbering eg. triger1, triger2 etc...)

starball
  • 20,030
  • 7
  • 43
  • 238
Dmitris
  • 3,408
  • 5
  • 35
  • 41

4 Answers4

115

You can use the following:

$("div[id^='triger']")

This will return all <div> with id starting (^=) with triger.

You can get more information about the various jQuery selectors in the jQuery docs:

API/Selectors

Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • 1
    Can we use it for multiple ids with the (^=). For ex.: to get the divs that starts with either 'trigger' or 'smart'? – Prasad Nov 10 '09 at 10:19
  • 6
    **@Prasad:** Sure! Simply use `$("div[id^='trigger'],div[id^='smart']")` – Andrew Moore Nov 10 '09 at 22:35
  • @AndrewMoore will this always return an ordered array? Or might this randomly sort my divs into the array? – Alan Scarpa Sep 19 '15 at 19:20
  • @Alan_s: It always returns the results in DOM order. (Except for a `.parents()` query; where the order is reversed since you are walking up the tree) – Andrew Moore Sep 20 '15 at 17:31
7

you can actually use a regular expression in a selector to achieve exactly what you are looking for, as such:

$("div:regex(id, yourRegularExpression)");

(Note: this does require the regex-selector plugin)

Someone asked a similar question here.

You can read all about regular expressions here.

As others have pointed out, you can achieve the same result like this:

$("div[id^='partOfID']");

by using a simple jQuery selector. For more complex selections, though, you will need to use the regex plugin or do it manually, as noted in the linked question.

good luck!

Community
  • 1
  • 1
Yuval Karmi
  • 26,277
  • 39
  • 124
  • 175
7

Select all div elements whose id attribute contains the string triger:

$('div[id*="triger"]');

There's more about using *= in the jQuery documentation: Attribute Contains Selector [name*="value"]

Alvaro
  • 11,797
  • 9
  • 40
  • 57
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
3
var trigerList = $("div[id^='triger']");
Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34