I have a list of 8 divs and need to add a sequence of class numbers to them using Jquery to style them individually. Need to add them to the 'content-block' div see example below.
The desired effect will be something like this:
<div class="wrapper">
<div id="content-block" *class="post1"*>
</div></div>
<div class="wrapper">
<div id="content-block" *class="post2"*>
</div></div>
I have added the script
**Javascript**
$('.post-block').each(function(i){
$(this).addClass('post' + i);})
but I need to link them with anchor links so I will need a way to add an ID to the post-block.
Desired effect
**HTML**
<div id="post1" class="post-block">
</div>
<div id="post2" class="post-block">
</div>
Many thanks
jsFiddle example
First, you can only use an ID once on a page. You can use classes many times on a page.
Because of this I made content-block
a class, and I made your various post1
, post2
... ids.
The function below will go through each of the elements that have the content-block
class within a wrapper
class, and it will add an appropriate id
to each one. For the callback function of each()
you can make use of the index
and value
as arguments. I created a separate num
variable, since index
starts at zero.
In the each
function, you could also use this
instead of value
.
The jQuery:
$.each($(".wrapper > .content-block"), function(index, value){
var num = index + 1;
$(value).attr("id","post"+ num);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With