... bunch of code ...
....">

Counting up for jQuery ID

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 can I use jQuery to basically identify each of these "ids" and then apply some jQuery to them? I'm new to this, so a little unsure? Sort of

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

      

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

thanks

+2


a source to share


4 answers


You could have used a substring selector to get most of the path:

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

      

... which will work better if you change the naming convention a bit so that the number is at the end. But I think I'm leaning towards using a different aspect of the struct (parent node) or class or attribute data-xyz

...



Edit A couple of substring selectors can do this:

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

      

This gets all those whose IDs start with "test-" and then filters out those that don't end with "yay". Anyway, close ...

0


a source


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



+3


a source


You can try something like:

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

      

or

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

      

or try to combine the two

Manual

+1


a source


you can do it like this:

$("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/

0


a source







All Articles