JS_is_awesome18
JS_is_awesome18

Reputation: 1757

How to dynamically append tailwindcss classes to each list item in JavaScript

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 class="text-3xl font-bold underline">
      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="#" class="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"></li>

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

Upvotes: 1

Views: 1748

Answers (2)

VMT
VMT

Reputation: 819

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

Upvotes: 1

0x45646A
0x45646A

Reputation: 177

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;

Upvotes: 0

Related Questions