How to enumerate page Divs with jquery?

Asked

Viewed 580 times

2

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

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 in this way:

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

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

  • The expected result is this HTML snippet? You want to include this content in <span> is?

1 answer

4


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

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

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

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

Another way, as said, using All Selector, would be so:

$("*[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 position of each div, we can use something like this, citing two other examples (besides the first one from 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, already rendered, this result:

1. Nome1
2. Nome2
3. Nome3
4. NomeN
  • That’s sort of how I solved it. Thank you for showing me other ways.

  • @Brunomarques yes, I saw that you had posted, but as I was already responding, I ended up including the answer =D

  • 1

    but it helped, its shape was more lean hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.