How to add class to element created using document.createElement?

Anthony picture Anthony · Mar 16, 2017 · Viewed 11.1k times · Source

I have managed to add a class to the ul element but I can't get the syntax right to add classes to the li and a elements. Can anyone help please?

<script>
    anchors.options.placement = 'left';
    anchors.add('.entry-content h2');
    generateTableOfContents(anchors.elements);

    // External code for generating a simple dynamic Table of Contents
    function generateTableOfContents(els) {
      var anchoredElText,
          anchoredElHref,
          ul = document.createElement('UL');
          ul.className = "uk-nav uk-nav-default";

      document.getElementById('table-of-contents').appendChild(ul);

      for (var i = 0; i < els.length; i++) {
        anchoredElText = els[i].textContent;
        anchoredElHref = els[i].querySelector('.anchorjs-link').getAttribute('href');
        addNavItem(ul, anchoredElHref, anchoredElText);
      }
    }

    function addNavItem(ul, href, text) {
      var listItem = document.createElement('LI'),
          anchorItem = document.createElement('A'),
          textNode = document.createTextNode(text);

      anchorItem.href = href;
      ul.appendChild(listItem);
      listItem.appendChild(anchorItem);
      anchorItem.appendChild(textNode);
    }
</script>

Answer

Hamik Hambardzumyan picture Hamik Hambardzumyan · Mar 16, 2017

before append li tag in the ul you need add your class then append li tag to ul tag like this

 var listItem = document.createElement('LI'); 
 listItem.className = 'someClassName';
 ul.appendChild(listItem);