简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM