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>
3
  • Possible duplicate of How to add a class to DOM element in JavaScript? Commented Mar 16, 2017 at 10:15
  • 2
    ??? listItem.className = '...'. If you can't see the correct rendering, please clarify your question. Commented Mar 16, 2017 at 10:15
  • 2
    What happens if the className property is set on listItem and anchorItem? Do they simply disappear? Commented Mar 16, 2017 at 10:15

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@sabithpocker No it doesn't, but it triggers one less reflow.
Thanks, this was helpful

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.