Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a sequence of numbers to divs

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

like image 718
Rob Avatar asked Jan 21 '23 15:01

Rob


1 Answers

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);
});
like image 118
Peter Ajtai Avatar answered Feb 01 '23 20:02

Peter Ajtai