How to enumerate page divs with jquery?

2

I would like to list all divs with spans of id="position" to simulate a rating.

Ex:

<div id="conteudo">    
  <div id="time"><span id="posicao">1.</span> Nome1</div>
  <div id="time"><span id="posicao">2.</span> Nome2</div>
  <div id="time"><span id="posicao">3.</span> Nome3</div>
  <div id="time"><span id="posicao">N.</span> NomeN</div>
</div>

I tried to generate it this way:

var divs = $("#conteudo").find("#posicao").toArray();
$.each(divs, function (index, value) {
    $("#posicao").append((index+1)+".");
});

But the numberings were only generated in the first span of id="position".

    
asked by anonymous 10.05.2015 / 02:45

1 answer

4

Only one element is listed because id exists. Since you are using #posicao , only one is returned. To list all, you can use All Selector .

There are a few ways to list, with jQuery, what you need. For example, fetch each span from each div from #conteudo , something like this:

$("#conteudo div span").each();

That is, everything that exists and obeys the path #conteudo > div > span will be returned.

Another way, as stated, using All Selector would look like this:

$("*[id*=posicao]").each();

Starting from this HTML:

<div id="conteudo">    
    <div id="time"><span id="posicao"></span> Nome1</div>
    <div id="time"><span id="posicao"></span> Nome2</div>
    <div id="time"><span id="posicao"></span> Nome3</div>
    <div id="time"><span id="posicao"></span> NomeN</div>
</div>

So to add in the position of each div , we can use something like this, citing two other examples (besides the first one above):

// este
$("#conteudo div").each(function(index) {
    $(this).children("#posicao").append((index + 1) + ".");
});

// ou este
$("*[id*=posicao]").each(function(index) {
    $(this).append((index + 1) + ".");
});

These examples will generate, rendered, this result:

1. Nome1
2. Nome2
3. Nome3
4. NomeN
    
10.05.2015 / 04:07