adams adams - 3 months ago 22
Javascript Question

jquery each function loop

I have multiple ul lists like below:

<ul>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
</ul>

<ul>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
</ul>

<ul>
<li><a href="#page/"></a></li>
<li><a href="#page/"></a></li>
</ul>


I want to count the total number of li and add from 1 to total count the number inside a span and update the href tag of the a as below:

<ul>
<li><a href="#page/1"><span>1</span></a></li>
<li><a href="#page/2"><span>2</span></a></li>
<li><a href="#page/3"><span>3</span></a></li>
<li><a href="#page/4"><span>4</span></a></li>
<li><a href="#page/5"><span>5</span></a></li>
</ul>

<ul>
<li><a href="#page/6"><span>6</span></a></li>
<li><a href="#page/7"><span>7</span></a></li>
<li><a href="#page/8"><span>8</span></a></li>
</ul>

<ul>
<li><a href="#page/9"><span>9</span></a></li>
<li><a href="#page/10"><span>10</span></a></li>
</ul>


How can I achieve this with jquery?

Answer

This should do it:

$('li').each(function (i) {
    i++;
    var link = $(this).find('a');
    link.attr('href', link.attr('href') + i);
    link.append('<span>' + i + '</span>');
});

In the code above we:

  • Iterate over each list item on the page using jQuery's .each() function
  • Increment the value of i by 1, so that we can count from 1 instead of from 0
  • Select and store a reference to the link element within the current list item that we're iterating on using jQuery's .find() method
  • Update the value of the href attribute using jQuery's .attr() method
  • And finally append a span tag to the link element, with the value of i as its contents using jQuery's .append() method