1

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>
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
Anthony
  • 657
  • 2
  • 10
  • 21
  • Possible duplicate of [How to add a class to DOM element in JavaScript?](http://stackoverflow.com/questions/1115310/how-to-add-a-class-to-dom-element-in-javascript) – Johan Willfred Mar 16 '17 at 10:15
  • 2
    ??? `listItem.className = '...'`. If you can't see the correct rendering, please clarify your question. – Teemu Mar 16 '17 at 10:15
  • 2
    What happens if the `className` property is set on `listItem` and `anchorItem`? Do they simply disappear? – Adrian Wragg Mar 16 '17 at 10:15

1 Answers1

9

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);