0

I am trying to add a class to an element when another element is clicked upon.

This is for a popup script and I'm trying to do it by toggling the CSS opacity property.

This is my HTML,

<span class="container">
  <span class="visible-text" onclick="addClassToPopUp()">
  </span>
  <span class="popup-text">
  </span>
</span>

And it repeats multiple times.

The visible text on the page is contained within the .visible-text class and the popup text is within the .popup-text. The opacity of the .popup-text class is zero.

I want to add a class to .popup-text when the .visible-text box is clicked. The class would overwrite the opacity to 1.

Now my question,

I can get a list of all classes using document.getElementsByClassName("popup-text"); but how do I narrow it down the current one?

Vinith Almeida
  • 1,421
  • 3
  • 13
  • 32

1 Answers1

1

One way is to limit it to the parent element

function addClassToPopUp(elem) {
   var popUp = elem.parentNode.getElementsByClassName("popup-text")[0]; 
   popUp.classList.toggle("active");  
}
.popup-text {
   display:none;  
}

.popup-text.active {
   display:block;  
}
<span class="container">
  <span class="visible-text" onclick="addClassToPopUp(this)">Hello
  </span>
  <span class="popup-text">World
  </span>
</span>
epascarello
  • 204,599
  • 20
  • 195
  • 236