JavaScript 获取 HTML 文档中的 h1 元素并更新唯一 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16591671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript get h1 elements in HTML document and update unique IDs
提问by ManUO
I have a legacy html document containing h1 elements which don't have ids. What I would like to achieve is to be able, using JavaScript, to get all h1(s) and then add to each a unique ID.
我有一个旧的 html 文档,其中包含没有 id 的 h1 元素。我想要实现的是能够使用 JavaScript 获取所有 h1(s),然后为每个添加唯一 ID。
I have searched but could not find a solution that works.
我已经搜索过,但找不到有效的解决方案。
回答by Ian
Try getting all of them with document.getElementsByTagName("h1")
. Loop through them, check if they have an id
, and work appropriately. Try:
尝试使用document.getElementsByTagName("h1")
. 循环遍历它们,检查它们是否有id
,并适当地工作。尝试:
var h1s = document.getElementsByTagName("h1");
for (var i = 0; i < h1s.length; i++) {
var h1 = h1s[i];
if (!h1.id) {
h1.id = "h1" + i + (new Date().getTime());
}
}
DEMO:http://jsfiddle.net/kTvA2/
演示:http : //jsfiddle.net/kTvA2/
After running the demo, if you inspect the DOM, you'll see 3 out of the 4 h1
elements have a new, unique id
. The one with the id
in the first place isn't changed.
运行演示后,如果您检查 DOM,您将看到 4 个h1
元素中有3 个具有新的、唯一的id
. 与一个id
摆在首位没有改变。
Note that this code needs to run after all elements are ready/rendered, which can be achieved by putting the code inside of a window.onload
handler. The demo provided is set up to implicitly run the code then.
请注意,此代码需要在所有元素都准备好/渲染后运行,这可以通过将代码放在window.onload
处理程序中来实现。提供的演示设置为隐式运行代码。
UPDATE:
更新:
With jQuery, you could use:
使用 jQuery,您可以使用:
$(document).ready(function () {
$("h1:not([id])").attr("id", function (i, attr) {
return "h1" + i + (new Date().getTime());
});
});
回答by km6zla
Use querySelectorAll()to get all of your header elements, then iterate over the result and generate yor unique id for each element.
使用querySelectorAll()获取所有标题元素,然后迭代结果并为每个元素生成您的唯一 id。
var headerElements = document.querySelectorAll('h1');
for(h in headerElements) {
if(headerElements[h] instanceof Element) {
headerElements[h].id=uniqueIDgenerator();
}
}