Reset Divs id by numbers in order

Asked

Viewed 40 times

-1

I am quite layman in Javascript and jQuery, and I needed to change the id of the Divs in numerical order.

For example:

<div id="1"></div>
<div id="2"></div>
<div id="8"></div>
<div id="11"></div>

and turn into:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>

Someone knows a method to do this?

2 answers

0

We can use the function each (function that performs a loop) to traverse all div of our HTML.

This function will loop all Divs (we specify that it will be on Divs in the command $(div)), and we also have the current loop index in the parameter index, and the current element (current div) in the parameter element. Now just define the new value for our attribute id, using the function attr() jquery.

$('div').each(function(index, element) { 
    // Já que o índice começa em zero então vamos definir o novo id como índice + 1
    $(element).attr('id', index + 1);
});

You can see the example working here: https://jsfiddle.net/o2gxgz9r/76342/

  • Thank you, that method worked too

0


Using pure Javascript you can create a nodelist with document.querySelectorAll("div") and then iterate with for changing the id’s:

var divs = document.querySelectorAll("div");
for(var x = 0; x < divs.length; x++){
   divs[x].id = x+1;
   
   // linha abaixo só para visualização
   console.log(divs[x].outerHTML);
}
<div id="1"></div>
<div id="2"></div>
<div id="8"></div>
<div id="11"></div>

  • Thank you very much man, I will use

Browser other questions tagged

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