Reputation: 3
I'm using Jquery for a small project and I have run into an issue.
I'm trying to create a small script that will look at a page, and automatically assign an ID to H1 headers based on the header text, i.e:
<h1> This is a Test </h1>
to
<h1 id="This_is_a_Test"> This is a Test</h1>
I've been able to select every H1, but I haven't been able to modify the ID based on the header text.
var $headers = $('.body h1);
$headers.attr("id", not sure exactly how to pass headers text to this?);
I'm obviously very much a novice, but would appreciate some help in this! Thanks!
Upvotes: 0
Views: 1496
Reputation: 192307
Use a jQuery's .attr()
with the callback option to read the text of the headers, converting it to snake case, and setting it as the id
:
var $headers = $('.body h1');
$headers.attr("id", function() {
return $(this)
.text() // get the h1 text
.trim() // remove spaces from start and the end
.toLowerCase() // optional
.replace(/\s/g, '_'); // convert all spaces to underscores
});
console.log($headers[0]);
console.log($headers[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
<h1>This is a Test </h1>
<h1>This is a another Test </h1>
</div>
Upvotes: 0
Reputation: 62626
If you want to do this for every h1
element you have in your page you can do something like that:
$(function() {
$('h1').each(function() {
$(this).attr('id', $(this).text().replace(/ /g, '_'))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Some text</h1>
<h1>Some other text</h1>
The function will take every h1
element, for each it will set the value of the id
attribute (using the attr
function) to the text()
of that h1
element (while changing every space with underscore).
Upvotes: 1
Reputation: 55750
First you need to generate the id
by using the text
method for h1
.
var $headers = $('.body h1'); // select the element
var text = $headers.text(); // get the text of the element
var id = text.trim().split(' ').join('_'); // split by space and join using _
$headers.attr("id", id);
Upvotes: 0