这是我的代码
<div id="box" class="something"> </div>
<div id="box" class="something"> </div>
<div id="box" class="something"> </div>
<div id="box" class="something"> </div>
<script>
var list = document.getElementsByClassName("something");
for (var i = 0; i <= list.length; i++) {
list[i].innerHTML = i;
}
</script>
答案 0 :(得分:0)
设置id属性
var list = document.getElementsByClassName("something");
for (var i = 0; i < list.length; i++) {
list[i].id = "box" + (i + 1);
}
答案 1 :(得分:0)
您的代码中存在错误:如果您从<=
开始,则<
应该只有0
!
一种可能的解决方案是使用node.setAttribute("attributeName", "attributeValue") method来设置/更改元素的属性(在本例中为id
):
<div id="box" class="something">A</div>
<div id="box" class="something">B</div>
<div id="box" class="something">C</div>
<div id="box" class="something">D</div>
<script>
var list = document.getElementsByClassName("something");
for (var i = 0; i < list.length; i++) {
list[i].setAttribute("id", "box" + i);
}
</script>
输出结果为:
<div id="box0" class="something"></div>
<div id="box1" class="something"></div>
<div id="box2" class="something"></div>
<div id="box3" class="something"></div>
如果可以使用JS库(例如jQuery),那么可以更简洁地编写转换:
$(".something").each(function(index) {
$(this).attr("id", this.id + index);
});
此代码导致与上面相同的输出。
评论的jQuery代码:
// find all elements with the class "something"
$(".something")
// call for each one of them
.each(
// the function with parameter = current index
function(index) {
// take the current element
$(this)
// and set the attribute id to the new value
.attr("id", this.id + index);
});