I've spent a few hours looking for a solution to this, but no joy. So...
I'd like to generate IDs based on the input. For example across a whole website;
<p class ="dynamic">I like cheese</p>
The outcome would be...
<p id ="i_like_cheese" class ="dynamic">I like cheese</p>
basically, whatever the text is, the id will mirror that. Any advice on where to start would be really appreciated!
Use querySelectorAll to get all elements with class dynamic then loop on each p and set id from innerText in wich you previsouly replace spaces by '_' with replaceAll
let ps = document.querySelectorAll('.dynamic');
ps.forEach(p=>{
p.id = p.innerText.replaceAll(' ','_');
console.log(p.id)
})
<p class ="dynamic">I like cheese</p>
<p class ="dynamic">I dont like cheese</p>
Thank you for all the suggestions and feedback. The solution I have implemented was from BZezzz.
let ps = document.querySelectorAll('.dynamic');
ps.forEach(p=>{
p.id = p.innerText.replaceAll(' ','_');
console.log(p.id)
})
A few people suggested the use case for this was a bad idea, so wanted to elaborate on what I've used this in conjunction with.
A WordPress plugin called "Table of Content" creates a TOC with anchor points a href="/#i-like-cheese"
I wanted to target specific elements on the page that would then populate the TOC anchor points as the plugin did not have all the functionality I required.
Use querySelectorAll to filter your DOM element by class name,
var lst = document.querySelectorAll('.dynamic')
Iterate through all the elements of the returned list, and set the id with respect to valid characters in the inner text of the HTML element. At this level, however, you must take into consideration the HTML version (4 or 5), because naming conventions differ between versions 4 and 5.
Version4: (https://www.w3.org/TR/html4/types.html#type-id) ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Version5: (https://www.w3.org/TR/html5-author/global-attributes.html#the-id-attribute) The id value must not contain any space characters.
To be on the safe side, I will assume that your website uses HTML4, and proceed accordingly.
//use regex to validate input with respect to HTML4 specifications
function isIdValid(id) {
let re = new RegExp(/^[A-Za-z]+[\w\-\:\.]*$/);
return re.test(id);
}
var counterID = 1;
function generateuuid() {
return "id_" + counterID.toString();
counterID+=1;
}
var lst = document.querySelectorAll('.dynamic');
lst.forEach(htmlelem => {
if (isIdValid(htmlelem.innerText.replaceAll(' ', '_'))) {
htmlelem.id = htmlelem.innerText.replaceAll(' ', '_');
}
else {
htmlelem.id = generateuuid();
//another approach would be to remove invalid characters from the inner
//text, and assign the value to htmlelem.id but this has a performance
//drawback, because it would require looping over each character.
}
})