PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to dynamically append tailwindcss classes to each list item in JavaScript

 July 22, 2022     append, arrays, for-loop, javascript, tailwind-css     No comments   

Issue

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?


Solution

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


Answered By - VMT
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing