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 badges5 Answers
Reset to default 3Another 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.