Search code examples
javascriptphphtmljquerydrupal

How to set element id based on innerHTML using javascript


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


Solution

  • 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>