Anthony Whitefield
Anthony Whitefield

Reputation: 75

Generate an ID from input - Javascript or Jquery

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!

Upvotes: 1

Views: 615

Answers (5)

Anthony Whitefield
Anthony Whitefield

Reputation: 75

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.

Upvotes: 1

bZezzz
bZezzz

Reputation: 1002

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>

Upvotes: 2

Elie Asmar
Elie Asmar

Reputation: 3165

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.

  }
})

Upvotes: 0

Vivek Vs
Vivek Vs

Reputation: 90

function nw_store_variable(ele) {

  let newVariable = ele.value;
  let st = ' ';
  let regX = new RegExp(st, "gim");
  // return this.newVariable.description;
  let strippedSpace = newVariable.replace(regX, '_');
  let properCase = strippedSpace.toLowerCase();
  let removerepeatedUndrScr = properCase.replace('--', '_'); //replace with recursive in future

  let e = document.querySelector('.dynamic');
  console.log(e)

  e.id = removerepeatedUndrScr;
  return
}
<p class="dynamic">

  <input onkeyup="nw_store_variable(this)"> I like cheese</p>
The outcome would be...
<p class="dynamic">I like cheese</p>

Upvotes: 0

Stender
Stender

Reputation: 2492

seems like a horrible idea... but

$( "p.dynamic" ).each(function() {
var newStringForID = $( this ).text();
var newID = newStringForID.replace(/\s+/g, '_').toLowerCase();
  $( this ).attr( "id", newID );
  console.log('dynamix ID set to '+newID )
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="dynamic">test 1</p>
<p class="dynamic">test 2</p>
<p class="dynamic">test 2 with more text </p>
<p class="dynamic">test 3</p>
<p class="dynamic">test4  gfdsg gfd </p>
<p class="dynamic">test5 <span>test</span></p>
<p class="dynamic">test6 <a href="#link">Link</a></p>
<p class="dynamic">test7</p>
<p class="dynamic">test8</p>

Upvotes: 0

Related Questions