Search code examples
javascriptclasszendesk

Adding a class and ID to headers using Javascript


The way that Zendesk's Help Centre works is by printing all the sections onto the page without giving them any unique identifier, so it's a pain if you want to implement any sort of scrollspy (updating a sidenav with where you are on the page), and most importantly anchors so that the sidenav actually works.

I'm not that technical and was wondering if anyone knew of a way to add an ID & class to a series of headers using JS?

I'm thinking for each h2 in section-tree-with-article, adding a unique ID, and a class that matches the h2's text?

Any thoughts?

Help Centre

Source code


Solution

  • You need to select all the h2 elements, iterate through them and set a class as well as an id with each iteration.

    I've simple set the innerHTML as the class. You can modify it according to your use case.

    var headers = document.querySelectorAll("div.section-tree-with-article h2");
    
    headers.forEach(function(header, idx) {
      header.className = header.textContent.replace(/\s/g, "-");      //You can modify this accordingly
      header.id = "uniqueID" + idx;            //And similarily the uniqueID
    })
    <div class="section-tree-with-article">
      <ul>
        <li class="section">
          <h2>Admin 0</h2>
        </li>
      </ul>
      <ul>
        <li class="section">
          <h2>Admin 1</h2>
        </li>
      </ul>
      <ul>
        <li class="section">
          <h2>Admin 2</h2>
        </li>
      </ul>
      <ul>
        <li class="section">
          <h2>Admin 3 4 5</h2>
        </li>
      </ul>
      <ul>
        <li class="section">
          <h2>Admin 4</h2>
        </li>
      </ul>
    </div>

    Here's the same solution in jquery:

    $("div.section-tree-with-article h2").each(function(index, value){
        var classToAdd = $(this).text();
        $(this).attr('class', classToAdd);
        $(this).attr('id', "uniqueID" + index);
    })