0

I want to add id for all the heading tag from dynamic content. The id should be based on innertext of the same element(this is to create the link for particular section).

Ex: if heading tag have <h1 class="title_tag">Key Programming Language</h1>, the output should be <h1 id="key-programming-language" class="title_tag">Key Programming Language</h1>

i am not sure how get innerHTML value into id. Please suggest me the solution using any javascript(or)jquery(or)PHP

4
  • 2
    You don't need those ids. What is the practical use-case for a bunch of the ids? How about a case there will be two or more elements with the same text content? Wait! The headers are targets of hash links? Commented Jul 8, 2021 at 17:58
  • Drupal has its own stack overflow network site at drupal.stackoverflow.com You may find help for your specific problem there. Commented Jul 8, 2021 at 17:58
  • @Teemu, there is no scenario of creating same element more than once. Because customer only going create the article. So i just want to create the id to point out the particular section using ID (like single page scrolling). Commented Jul 8, 2021 at 18:05
  • Overly complex ids might still be a headache, wouldn't 'header' + runningID do? Commented Jul 8, 2021 at 18:12

3 Answers 3

3

const convertToKebabCase = (string) => {
  return string.replace(/\s+/g, '-').toLowerCase();
}

const h1 = document.querySelectorAll("h1");
h1.forEach(el=>{
  const kebabCaseText = convertToKebabCase(el.innerText);
  el.id = kebabCaseText;
})
<h1 class="title_tag">Key Programming Language</h1>

Sign up to request clarification or add additional context in comments.

Comments

1

This what you're trying to do?

    $("h1").each(function(){
        
        var newId = $(this).text().replace(" ", "-");
        //console.log(newId);
        $(this).attr('id', newId);
    });

Comments

0

or pure Javascript:

var elements = document.getElementsByTagName("1");
for (i = 0; i < elements.length; i++) {
    elemelements[i].id = elements[i].innerHTML;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.