开发者

Is it possible to re-assign a div's childs class in consecutive order with Jquery

I have the following situation where my divs childs id's need to be renamed in consecutive order starting from 1.

eg.

<div id="parent">  
    <div id="child-108"></div>
    <div id="child-99"></div>
    <div id="child-9"></div>
    <div id="child-18"></div>
    <div id="child-64"></div>
</div>

converted via JQuery or regular Javascript into:

<div id="parent">  
    <div id="child-1"></div>
    <div id="child-2"></div>
    <div id="child-3"></div>
    &开发者_如何学Golt;div id="child-4"></div>
    <div id="child-5"></div>
</div>

Any help would be great!


Sure, you can do that with the each function:

$('#parent > div').each(function(index) {
    this.id = 'child-' + (index + 1);
});

The function you pass into each is called with this pointing at the DOM element and the index argument giving the index (starting with 0) within the selected elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜