DesignSubway DesignSubway - 1 month ago 7
CSS Question

JQuery get link and add variable depending on nth number

I have a list set up containing links. Before this list is another link, this is the html:

<div class="catItemBody">
<div class="catItemImage">
<a href="index.html">Link</a>
</div>
<ul class="sigProBetton">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>

<div class="catItemBody">
<div class="catItemImage">
<a href="index2.html">Link</a>
</div>
<ul class="sigProBetton">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>


There are multiple .catItemBody on the page, each containing a unique link.

I also have some jquery which takes the first link (.catItemImage a) and applies it to each of the links in the list. What I am trying to do is modify this link depending on the list items nth number. I have been experimenting with the first link item using the following jQuery:

$(document).ready(function() {

$('.catItemBody').each(function(){
var linkitem = $('.catItemImage a', this).attr('href');
if ($('ul.sigProBetton li').is(':nth-child(1)')){
$('ul.sigProBetton li a', this).attr('href' , linkitem+'?image=1');
} else {
$('ul.sigProBetton li a', this).attr('href' , linkitem);
}
});

});


Eventually I want to build on this so that the link in the first item has the URL variable of ?image=1, then the second will have ?image=2 etc... I need the 'count' to reset so that the list in the next .catItemBody will start again at ?image=1.

At the moment, each link has the variable ?image=1 which is not ideal. I have set up a jsFiddle at http://jsfiddle.net/Dyfe6/.

EDIT
All of your answers seem to work but the problem is that I have more than one
.catItemBody
on the page, an updated jsfiddle can be found at http://jsfiddle.net/Dyfe6/9/

Answer

No need to use nth-child.

I didn't understand if you wanted to reset or not the image count, so here it is not resetted :

$(document).ready(function () {
    var count = 0;
    $('.catItemBody').each(function () {
        var linkitem = $(this).find('.catItemImage a').attr('href');
        $(this).find('ul.sigProBetton li').each(function () {
            count++;
            $(this).find('a').attr('href', linkitem + '?image=' + count);
        });

    });
});

jsFiddle : http://jsfiddle.net/Dyfe6/11/

And here it is resetted :

$(document).ready(function () {
    $('.catItemBody').each(function () {
        var linkitem = $(this).find('.catItemImage a').attr('href');
        $(this).find('ul.sigProBetton li').each(function (index) {
            $(this).find('a').attr('href', linkitem + '?image=' + (index + 1));
        });

    });
});

http://jsfiddle.net/Dyfe6/12/