I am working on a wordpress navigation menu and trying to simlpy (of course, dynamically) add number inside a span tag for each menu li item.

So I created a "top menu" using the wordpress custom menu function then I used a simple jquery function to add a "span" tag inside each tag like so:

$("#top .menu ul li a").prepend("<span></span>");

This generated the following HTML:

<li><a href=""><span></span>Menu Item</a></li>
<li><a href=""><span></span>Menu Item</a></li>
<li><a href=""><span></span>Menu Item</a></li>
<li><a href=""><span></span>Menu Item</a></li>

Thats exactly what I want as step #1 Now, what I am trying to get is a simple jquery function which will dynamically add a following number inside each divs maybe using a variable or something. The out put needs to be:

<li><a href=""><span>1</span>Menu Item</a></li>
<li><a href=""><span>2</span>Menu Item</a></li>
<li><a href=""><span>3</span>Menu Item</a></li>
<li><a href=""><span>4</span>Menu Item</a></li>

etc.. etc..

should be a very simple jquery function. just can't find it. any suggestions?

Thanks a lot!

closed as off topic by Geert, Michael, fuxia Dec 17 '12 at 16:21

Questions on WordPress Development Stack Exchange are expected to relate to WordPress within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.

$("#top .menu ul li").each(function(i, el) {
    $(this).children('a').prepend("<span>" + (i+1) + "</span>");

or much better

$("#top2 .menu ul li").each(function() {
    var $this = $(this);
    $this.children('a').prepend("<span>" + ($this.index()+1) + "</span>");

check this out for the difference... http://jsfiddle.net/reigel/aAYCt/


You should need something like that

var menuIndex = 0; 
jQuery('#top .menu ul li a span').each(function(){ 

Anyway, you could do it in once, by creating and filling the span at the same time.

  • 1
    If you like the answer, could you vote it up? I agree Reigel's one is more complete, so it's his answer the one that should be accepted, but you can vote more than one ;) – Xavi Ivars Dec 19 '12 at 19:08
function fill_numbers_in_span() {
  jQuery("#top .menu ul li a").each(function(index){

This function will do the trick. It prepends span as well as adds the correct index. Just make sure that the selector "#top .menu ul li a" is correct.

  • Great @Mridul Aggarwal Thanks! I will try that out – gil hamer Dec 18 '12 at 14:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.