How can I do that

<ul>
  <li class="section"><a href="index.html">Home</a></li>
  <li class="section"><a href="files/articals/articals.html">Articals</a></li>
  <li class="section"><a href="files/tricks & skills/tricks.html">Tricks & Skils</a></li>
  <li class="section"><a href="files/about/about.html">About</a></li>
</ul>

In the previous code, how can I in (JS) add & delete a class by clicking the button for example.
I searched a lot on the internet but couldn’t find anything I could understand

Thank In advance :slightly_smiling_face:

Hi @albaraa_1949

I think the easiest way to add, remove or toggle classes is using:


Generally, you should add an event listener to your button
addEventListener('click', function() {})

in its function you select the element where you want to change the classes

document.querySelector()

and then you use

classlist.add()

(or similar function) on the element to change its classes. In this article is a short example of a <span> that toggles its class when clicked: https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle

To give an specific solution you should tell us some more details:

  • Has every <li> its own button?
  • Is the button inside or outside the element it should change?
  • Should the classes on all <li> be add/removed together?
  • Is a button really needed or shall a click on the <li> element itself change its class?

I hope that gives a starting point. I’m happy to provide a more specific solution when I understand the details.

Michael

.I apologize for not fully explaining the problem
:grin: But I was able to get started thanks to your explanation

1 Like

No worries! :slightly_smiling_face:
Nice to hear that. Just ask if you need more help.

1 Like