0

Objective

When my button is clicked, I want to add a class name to a different element.

My button code:

<a href="#" class="elementor-button-link elementor-button elementor-size-lg" role="button" id="explorebuttonid">

Class before button is clicked. This is not the same class as the button:

<div class="elementor-menu-cart__container elementor-lightbox">

Desired class after button is clicked. This is not the same class as the button:

<div class="elementor-menu-cart__container elementor-lightbox elementor-menu-cart--shown">

Problem

When I try the below, nothing happens when the button is clicked.

What I have tried

I have tried implementing these two together:

1) Add a click listener: Link

2) Insert a function to alter the class name: Link

<script>
document.getElementById("explorebuttonid").addEventListener("click", clicky1);

function clicky1() {
var clicky2 = document.getElementsByClassName("elementor-menu-cart__container elementor-lightbox");

clicky2.className += "elementor-menu-cart--shown";

}
</script>
umek
  • 17
  • 6
  • 1
    `getElementsByClassName` will returns a `HTMLCollection` then you have to iterate every one to apply some effect – Christian Carrillo Feb 12 '20 at 13:27
  • 1
    `getElementsByClassName` returns an ` HTMLCollection` which is similar to an array of HTML elements you have to iterate through the array and apply the class to the elements or you can use `getElementById("explorebuttonid")` and apply the class to the element – Nijeesh Joshy Feb 12 '20 at 13:29
  • Try it and then in script function myFunction() { var element = document.getElementById("myDIV"); element.classList.add("mystyle"); } – Nitin tiwari Feb 12 '20 at 13:31
  • @NijeeshJoshy thanks for the feedback. However, I forgot to mention that the class I want to change is separate from the button. Thus, I cannot grab it by ID. – umek Feb 12 '20 at 13:31
  • @Nitintiwari thanks. But I can't amend the HTML code on the page so that wouldn't be possible. – umek Feb 12 '20 at 13:32

0 Answers0