Control Freak
Control Freak

Reputation: 13243

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.

Upvotes: 5

Views: 159

Answers (5)

ShankarSangoli
ShankarSangoli

Reputation: 69915

If you dont know whether it starts or endswith any string then you can try *= selector which will look within the attribute value.

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

Upvotes: 1

Dennis
Dennis

Reputation: 32608

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")

Upvotes: 2

FishBasketGordo
FishBasketGordo

Reputation: 23142

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_"')

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

You can use an Attribute Starts With selector:

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

Upvotes: 4

Matthew Abbott
Matthew Abbott

Reputation: 61599

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.

Upvotes: 1

Related Questions