英文:
How can I loop through some divs that share a class and apply a unique id to them?
问题
Sure, here's the translated code part you requested:
我有一组具有相同类名但没有独立id的div。它们在html中显示的顺序很重要,必须保留。我需要能够循环遍历由`document.getElementsByClassName(className);`给出的元素列表,并为它们每个提供一个形式为`"tile-1" "tile-2"`等的唯一id。
我认为像这样的代码可能有效,但很快我意识到这不会起作用:
```js
const getTiles = document.getElementsByClassName(tileClass);
let n = 1;
for (e in getTiles){
let i = "tile-" + n;
e.setAttribute("id", i);
n++;
}
我希望数组中的每个元素都能应用setAttribute
,但我错了。
有什么建议吗?
<details>
<summary>英文:</summary>
I have a set of divs that share a class name, but have no individual id. The order in which they show up in html is important and must be preserved. I need to be able to loop through the list of elements given by `document.getElementsByClassName(className);` and give them each a unique id in the form `"tile-1" "tile-2" etc`.
I thought something like this may work but I soon came to realise that this would not work:
```js
const getTiles = document.getElementsByClassName(tileClass);
let n = 1;
for (e in getTiles){
let i = "tile-" + n;
e.setAttribute("id", i);
n++;
}
I was hoping it would be as easy as each element in the array having the setAttribute
applied to them but I was wrong.
Any suggestions?
答案1
得分: 1
尝试一下:
let i = 1;
document.querySelectorAll('.post').forEach(el => {
el.id = 'title-' + i;
i++
})
<div class="post">
</div>
<div class="post">
</div>
<div class="post">
</div>
<div class="post">
</div>
英文:
try that
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let i = 1;
document.querySelectorAll('.post').forEach(el => {
el.id = 'title-' + i;
i++
})
<!-- language: lang-html -->
<div class="post">
</div>
<div class="post">
</div>
<div class="post">
</div>
<div class="post">
</div>
<!-- end snippet -->
答案2
得分: 0
如评论中由 @Barmar 指出,我需要在for循环中使用 of
而不是 in
。现在按预期运行。
英文:
As pointed out by @Barmar in the comments, I needed to use of
instead of in
in the for loop. Works as intended now.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论