1

Let's look at the following code:

<ul>
  <li>What is jQuery?</li>
  <li>What is HTML?</li>
  <li>What is CSS</li>
</ul>

What I want to be able to do is to append after each question (into another div) this kind of text: question 1/3, question 2/3 and question 3/3...

I know length() calculates the total number of matched elements so that would give me the number "3" that goes after the "/" but how do I display the current question's number? I know it's something related to index() but I am not sure on how to do this.

Thank you!

hexacyanide
  • 88,222
  • 31
  • 159
  • 162

3 Answers3

1

I'd suggest:

var size = $('li').length;
$('li').each(function(i){
    $('<div />', {'text' : 'Question ' + (i+1) + '/' + size}).appendTo(this);
});

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

demo: http://jsfiddle.net/tGLQk/1

use each

html

<ul>
  <li>What is jQuery?</li>
  <li>What is HTML?</li>
  <li>What is CSS</li>
</ul>

js

var count = $("ul li").length;
$("ul li").each(function(key,val){
 this.innerHTML += " " + (key+1) + "/"+count;
});
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • there is no guarantee that `each` will be in the correct order. – Dave Mar 09 '13 at 01:22
  • http://stackoverflow.com/questions/9843142/change-in-order-for-each-in-firefox-and-chrome – Dave Mar 09 '13 at 01:31
  • @Dave - Those are objects, not dom elements. That question is not evidence of dom elements being shown out of order from using `.each`. Reproduce the issue in a jsfiddle if you believe that they will be out of order, but I highly doubt that to be the case. When jquery navigates the DOM it does it in order of the element being attached to the dom. – Travis J Mar 09 '13 at 01:33
  • Seems you're right according to this: http://stackoverflow.com/questions/12988535/make-each-function-carry-out-in-order-of-first-element-to-last. I'd like to find a more definitive source but that should be enough to go on. I assumed older (or newer) internet explorers might mess it up, because they usually do. – Dave Mar 09 '13 at 01:39
  • @Dave - jQuery checks to see if there is a length property defined when using `each`. If it is not there then it uses `for( in )` which is what causes the order to not be guaranteed. However, all `HTMLElements` sit inside of `NodeList`s. The `NodeList` has a length property and thus `each` uses it to iterate using a normal `for()` loop guaranteeing it to be in order. – Travis J Mar 09 '13 at 01:42
-1

There's no guarantee that .each will be in the correct order, but you can do this with CSS. See this fiddle for an example: http://jsfiddle.net/NCzsG/

(note that if you have more than one list, you'll need to use .each to iterate through each ul running this on the lis of each one)

Dave
  • 44,275
  • 12
  • 65
  • 105
  • Only the counters. The total still needs to be given by JavaScript or written right into the HTML, as far as I'm aware. – Dave Mar 09 '13 at 01:46