Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a class (related to tailwind) using javascript doens't work

I have a button with a PLUS svg image in it. On click, I what that Plus svg to disappear. I checked in console and the function works fine, the class "visible" is removed and the class "invisible" is added. But in the UI the Plus svg doesn't disappear. "Invisible" is a class in Tailwind that should make an item to be hidden.

const BtnAddEle = document.querySelector(".addEle");
const plusSvg = document.querySelector(".addElePlus");

BtnAddEle.addEventListener("click", function () {
  plusSvg.classList.remove("visible");
  plusSvg.classList.add("invisible");
});
like image 704
Yamyyuky Avatar asked Nov 18 '25 13:11

Yamyyuky


2 Answers

The reason why it is not working for you is that-

To have tailwind classes to work from JS file you have to define the path of js file in the content portion of tailwind.config.js file. Example:

content: ["./*.{html,js}", "./src/**/*.{html,js}"]

Using this, your tailwind compiler will know that you are trying to add a css class from your JS file and that class will appear in the output css file.

Content Configuration is mentioned and explained in details - Here [Official Documentation]

like image 71
Mohammad Mustak Absar Khan Avatar answered Nov 21 '25 01:11

Mohammad Mustak Absar Khan


This is happening because tailwind only adds class styles which you have used in the final CSS file

So you can do something like this

const BtnAddEle = document.querySelector(".addEle");
const plusSvg = document.querySelector(".addElePlus");

BtnAddEle.addEventListener("click", function () {
  plusSvg.style.visibility = "hidden"
});
like image 21
Heet Vakharia Avatar answered Nov 21 '25 03:11

Heet Vakharia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!