0

A little stuck here with the following code that works opening a modal on click with the class name '.pl-modal', however when using the class in multiple places it only works on the first element.

I'd like to understand why it doesn't work on multiple elements with the same class.

let player = null;
const $ = function (el) {
  return document.querySelector(el);
};
$(document).on("click", function () {
  $(".pl-modal").classList.add("pl-modal-active");
  player.playVideo();
},false);

function popupClose() {
  $(".pl-modal").classList.remove("pl-modal-active");
  $(".pl-hidden").style.display = "block";
  player.stopVideo();
  player.setPlaybackRate(1);
}
window.onclick = function (event) {
  if (event.target == $(".pl-modal")) {
    popupClose();
  }
};

2 Answers 2

1

Use query selector all and foreach:

document.querySelectorAll('.class1').forEach(element => element.addEventListener('click', event => {
  console.log(event.target.innerText);
}));
<div class="class1">text1</div>
<div class="class1">text2</div>
<div class="class1">text3</div>

Read here for more

Sign up to request clarification or add additional context in comments.

Comments

0

You have to use document.querySelectorAll instead of document.querySelector. querySelector only returns the first element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.