JavaScript 获取 HTML 文档中的 h1 元素并更新唯一 ID [英] JavaScript get h1 elements in HTML document and update unique IDs

查看:61
本文介绍了JavaScript 获取 HTML 文档中的 h1 元素并更新唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧的 html 文档,其中包含没有 id 的 h1 元素.我想要实现的是能够使用 JavaScript 获取所有 h1(s),然后为每个添加唯一 ID.

我进行了搜索,但找不到有效的解决方案.

解决方案

尝试使用 document.getElementsByTagName("h1") 获取所有这些.循环遍历它们,检查它们是否有 id,然后正常工作.试试:

var h1s = document.getElementsByTagName("h1");for (var i = 0; i < h1s.length; i++) {var h1 = h1s[i];如果(!h1.id){h1.id = "h1" + i + (new Date().getTime());}}

演示: http://jsfiddle.net/kTvA2/>

运行演示后,如果您检查 DOM,您会看到 4 个 h1 元素中有 3 个具有新的、唯一的 id.id 放在第一位的那个没有改变.

请注意,此代码需要在所有元素准备好/渲染后运行,这可以通过将代码放在 window.onload 处理程序中来实现.提供的演示设置为隐式运行代码.

<小时>

更新:

使用 jQuery,您可以使用:

$(document).ready(function () {$("h1:not([id])").attr("id", function (i, attr) {返回 "h1" + i + (new Date().getTime());});});

演示: http://jsfiddle.net/kTvA2/7/

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.

I have searched but could not find a solution that works.

解决方案

Try getting all of them with document.getElementsByTagName("h1"). Loop through them, check if they have an id, and work appropriately. Try:

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/

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.

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.


UPDATE:

With jQuery, you could use:

$(document).ready(function () {
    $("h1:not([id])").attr("id", function (i, attr) {
        return "h1" + i + (new Date().getTime());
    });
});

DEMO: http://jsfiddle.net/kTvA2/7/

这篇关于JavaScript 获取 HTML 文档中的 h1 元素并更新唯一 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆