使用JavaScript在内容中设置标头ID属性

时间:2010-11-10 15:51:14

标签: javascript jquery html

使用JavaScript从内容中设置标头ID的最简单方法是什么,并为连字符交换空格并使其成为小写。

例如,如果标题是:

<h1>Header one content</h1>

我们如何才能将其改为:

<h1 id="header-one-content">Header one content</h1>

由于

5 个答案:

答案 0 :(得分:3)

因为不需要jQuery

var tags = document.getElementsByTagName("h1");
for (var i=0, h1; h1 =  tags[i]; i++) {
  h1.id = h1.innerHTML.toLowerCase().replace(" ", "-");
}

答案 1 :(得分:3)

另一种方法,迭代所有H1标签并执行操作:

$("h1").each(function() {
    var hyphenated = $(this).text().replace(/\s/g,'-');
    $(this).attr('id',hyphenated);
  }
);

答案 2 :(得分:1)

由于您在标签中提到了jQuery,我假设您欢迎它,所以:

jQuery("h1:first").attr("id", "header-one-content");

已更新:抱歉,没有仔细阅读这个问题。这是一个更新:

来自jQuery网站:

示例:根据页面中的位置设置div的ID。(已编辑)

<h1>Heading One</h1>
<h1>Heading Two</h1>
<h1>Heading Three</h1>

使用Javascript:

$("h1").attr("id", function (arr) {
    return "header-" + arr;
});

结果:

<h1 id="header-0">Heading One</h1>
<h1 id="header-1">Heading Two</h1>
<h1 id="header-2">Heading Three</h1>

更多信息:jQuery.attr

答案 3 :(得分:0)

使用JQuery:

var inner = jQuery("h1:first").html();
inner.replace(" ", "-");
jQuery("h1:first").attr("id", inner);

答案 4 :(得分:0)

使用JavaScript:

var title = document.getElementsByTagName('h1')[0]; 
//it returns a array of h1 tags. For this example I only obtain the first position.
//you can change the index of the array to obtain your 'h1'. It depends on the position. You also can to cover the array by a for loop.

title.id = title.innerHTML.replace(/ /g, "-").toLowerCase()
//The /g operator is to define a global replace.