Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a selector using indexOf

Like

    <div id="box_1">
    <div id="box_2">
    <div id="box_3">

If i want to get all id's starting with 'box_' how can i do it something like this..

    $("#box_" + anything )

Unfortunately wrapping the div's won't work because it will get all the other divs in side and between the box divs.

I guess i can give them all another class and reference it like that, but just wondering if there's something like this out there.. thanks.

like image 334
Control Freak Avatar asked Aug 29 '11 15:08

Control Freak


4 Answers

You can use an Attribute Starts With selector:

$("div[id^=box_]");
like image 152
Frédéric Hamidi Avatar answered Oct 30 '22 05:10

Frédéric Hamidi


It is possible with the attribute starts with selector as others have mentioned, but it might be better to give each element a class:

<div id="box_1" class="box"></div>
<div id="box_2" class="box"></div>
<div id="box_3" class="box"></div>

Select with:

$(".box")
like image 25
Dennis Avatar answered Oct 30 '22 07:10

Dennis


Yep:

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

In this case, because you are trying to use the ID selector, its better to switch to an element selector, combined with an attribute selector.

like image 41
Matthew Abbott Avatar answered Oct 30 '22 07:10

Matthew Abbott


You can use an attribute selector:

$('[id^="box_"')

That will give you all elements whose id starts with "box_". If you need to, qualify it with an element:

$('div[id^="box_"')
like image 30
FishBasketGordo Avatar answered Oct 30 '22 07:10

FishBasketGordo