views:

63

answers:

4

Hi Guys,

I have the following HTML structure

<div id="test-1-yay"></div>
... bunch of code ...
<div id="test-2-yay"></div>
... bunch of code ...
<div id="test-3-yay"></div>

I was wondering how I can use jQuery to basically identify each of these "id's" and then apply some jQuery to them ? I'm new to this so little unsure ? Something like

if $('#test-1-yay' || '#test-2-yay' || '#test-3-yay') {
do stuff to all ID's
}

But the prob is I want this to continue as it could go to #test-201-yay, #test-202-yay etc ?

Thx

+3  A: 

Why don't you add a class to the divs?

svinto
That or get them based on the parent element $('#parentid div')
Tom
ah ok - is it possible to iterate the div id or ?
Tom
This is a valid *alternative* but does not answer the actual question.
patrick dw
A: 

You could use a substring selector to get most of the way there:

var divs = $('div[id^=test-]'); // All divs with IDs starting with "test-"

...which would work better if you changed the naming convention a bit so the number was at the end. But I think I'd lean toward using some other aspect of the structure (the parent node), or a class, or a data-xyz attribute...

Edit A pair of substring selectors can do it:

var divs = $('div[id^=test-]').filter("div[id$=yay]");

That gets all of the ones whose IDs start with "test-" and then filters out the ones that don't end with "yay". Close, anyway...

T.J. Crowder
thx :) [and to everyone else as well]
Tom
A: 

you could do it like that:

$("div[id^=test-]").each(function(){ //selects all dives having the string 'test-' in it
$that = $(this) 
$that.text($that.attr("id").split("-")[1]) //splits the sting by "-" and gives you out the middle part (in your case the number)
})

test it here http://jsfiddle.net/aj5Qk/1/

meo
+1  A: 

You could try something like:

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

or

$("div[id$='yay']")

or try to combine the two

Manual

Nebo