Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

  }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda