0

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:

<ul>
<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>
</ul>

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:

<ul>
<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>
</ul>

etc.. etc..

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

Thanks a lot!

2
$("#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/

| improve this answer | |
0

You should need something like that

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

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

| improve this answer | |
  • 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
0
function fill_numbers_in_span() {
  jQuery("#top .menu ul li a").each(function(index){
    jQuery(this).prepend("<span></span>").find('span').text(index+1);
  });
}

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.

| improve this answer | |
  • 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.