Home > Software design >  Generate an ID from input - Javascript or Jquery
Generate an ID from input - Javascript or Jquery

Time:10-27

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!

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

  }
})
  • Related