最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Set header id attribute from content with JavaScript - Stack Overflow

programmeradmin0浏览0评论

Using JavaScript what’s the simplest way to set a headers id from it’s content and swap spaces for hyphens and make lowercase.

For example, if header is:

<h1>Header one content</h1>

how can we change that to:

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

Thanks

Using JavaScript what’s the simplest way to set a headers id from it’s content and swap spaces for hyphens and make lowercase.

For example, if header is:

<h1>Header one content</h1>

how can we change that to:

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

Thanks

Share Improve this question edited Feb 1, 2015 at 16:29 Deduplicator 45.8k7 gold badges72 silver badges123 bronze badges asked Nov 10, 2010 at 15:51 JamesJames 172 silver badges5 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

Another way, iterating through all H1 tags and performing the operation:

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

Since jQuery is not really needed

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

Since you mentioned jQuery in your tags I assume you wele it, so:

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

Updated: Sorry, didn't read the question carefully enough.. Here's an update:

From the jQuery website:

Example: Sets id for divs based on the position in the page. (edited)

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

Javascript:

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

Results in:

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

More info: jQuery.attr

using JQuery:

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

Using 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.
发布评论

评论列表(0)

  1. 暂无评论