Home > Mobile >  How to dynamically append tailwindcss classes to each list item in JavaScript
How to dynamically append tailwindcss classes to each list item in JavaScript

Time:05-16

I am attempting to add Tailwindcss styling classes to list items appended to an HTML document from an array:

const array1 = ['one', 'two', 'three', 'four', 'five']

for (let i = 0; i < array1.length; i  ) {
  let li = document.createElement('li')
  document.querySelector('#newList').append(array1[i], li)
}

The querySelector is bound to an UL element in a tailwindcss template:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body>
    <h1 >
      My Todo list
    </h1>
    <div>
      <ul id="newList"></ul>
    </div>    
    <script src="app.js"></script>
  </body>
</html>

I want each LI element to have the following tailwindcss classes:

<li href="#" ></li>

How can I configure either the JS or HTML to dynamically append these classes to each LI element from the array?

CodePudding user response:

If you want to append to a node as child, i think use appendChild() like this:

const array1 = ['one', 'two', 'three', 'four', 'five']

for (let i = 0; i < array1.length; i  ) {
  let li = document.createElement('li')
  li.innerHTML = array1[i]
  li.classList.add('block', 'p-6', 'max-w-sm', 'bg-white', 'rounded-lg', 'border', 'border-gray-200', 'shadow-md', 'hover:bg-gray-100', 'dark:bg-gray-800', 'dark:border-gray-700', 'dark:hover:bg-gray-700')
  document.querySelector('#newList').appendChild(li)
}

CodePudding user response:

It can be done by appending class names to a classList on DOMElement. Take a reference from here - https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

It would look something like:

   let x = document.createElement('div');
   x.classList.add('className');

NOTE: Additionally, the li elements should be appended to the ul#newList element instead of document;

  • Related