JS event listener doesn't work on elements after insertion

259 Views Asked by At

I'm changing document language from Arabic to English by setting the dir attribute to rtl, with that happening I'm hiding the parent div date-and-language and adding it to another place in the document using insertAdjacentHTML, the problem with this is that the event listener doesn't work on its child .language anymore ( after insertion with same classes names ), why doesn't it ?

const language = document.querySelector(".language");
const languageOptions = document.querySelector(".language-options");
const mainHeaderOptions = document.querySelector(".main-header-options");
const dateAndLanguage = document.querySelector(".date-and-language");


const changeLanguage = (e) => {
  languageOptions.classList.toggle("hide");
};

language.addEventListener("click", (e) => changeLanguage(e));

const toEnglish = () => {

  document.documentElement.setAttribute("dir", "ltr");
  dateAndLanguage.style.display = "none";

  const html = `
    <div class="language">
      <i class="fa-solid fa-earth-europe icon"></i>
      Language
      <i class="fa-solid fa-angle-down icon"></i>
      <div class="language-options hide">
        <p class="arabic">عربي</p>
        <p class="english">English</p>
      </div>
    </div>
  `;
  mainHeaderOptions.insertAdjacentHTML("beforeend", html);
};

english.addEventListener("click", () => toEnglish());

I tried to attach the listener on document like this :

const changeLanguage = (e) => {
  if(e.target.classList.contains("language"){
    languageOptions.classList.toggle("hide"); // doesn't work
}

};

document.addEventListener("click", (e) => changeLanguage(e));
0

There are 0 best solutions below