Reseting the id from tag elements with jquery

Given the following html:

<div>
    <div id="element-0"></div>
    <div id="element-1"></div>
    <div id="element-2"></div>
    <input id="element-3"></input>
    <div id="element-4"></div>
    <div id="element-5"></div>
    <div id="element-6"></div>
</div>

if the element with the ids' 2 and 4 were to be removed how i could reset (with jquery or javascript if it is easier) the ids of all these eleements with the final result of:

 <div>
    <div id="element-0"></div>
    <div id="element-1"></div>
    <input id="element-2"></div>
    <div id="element-3"></div>
    <div id="element-4"></div>
</div>

Thanks for the help!

Upvotes: 0

Views: 76

Answers (3)

Ethan Brown
Ethan Brown

Reputation: 27282

The other answers are okay, but may not be robust enough. @Xander's answer, for example, doesn't take into account that one of the elements is an input not a div. @thecodeparadox's answer relies on every child of the enclosing div having an "element-" ID.

To do this thoroughly, you'll have to walk through all elements in the DOM and see if their IDs start with "element-", then change the ID accordingly.

I started by writing a function to get all elements that start with "element-":

function getElements() {
  return $('html').find('*').filter( function() {
    var id = $(this).attr('id');
    return id && id.indexOf( "element-" ) == 0;
  } );
}

Then a function to reorder the IDs:

function reorderIds() {
  var idx = 0;
  getElements().each( function() {
    $(this).attr( 'id', 'element-' + idx++ );
  } );
}

You can see my jsfiddle here: http://jsfiddle.net/22CzQ/4/

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

<div id="elements">
    <div id="element-0"></div>
    <div id="element-1"></div>
    <div id="element-2"></div>
    <input id="element-3"></div> // your markup has error here remove the </div>
    <div id="element-4"></div>
    <div id="element-5"></div>
    <div id="element-6"></div>
</div>


$('#elements').children().each(function(index, val) {
  $(this).attr('id', 'element-' + index);
});

Upvotes: 0

Alex
Alex

Reputation: 35407

function resetIndexes() {
    var els = $('div *'), i;

    for(i = 0; i < els.length; i++){
        els.eq(i).attr('id', 'element-' + i);
    }
}

Upvotes: 1

Related Questions