0

I would like to add attribute "aria-label=test1" when it is fa-chevron-left and "aria-label=test2" on fa-chevron-right.

"aria-label=test1" should be there on load (default). Could anyone show me how to code it for here?

function s(e) {
  const t = n(),
    c = document.querySelector(".nav-container"),
    o = document.querySelector(".content-container"),
    s = document.querySelector(".slide-btn i.fas");
  switch (e) {
    case "toggle":
      c.classList.toggle("slided"),
        s.classList.toggle("fa-chevron-right"),
        s.classList.toggle("fa-chevron-left"),
        t && o.classList.toggle("slided");
      break;
    case "show":
      c.classList.remove("slided"),
        s.classList.remove("fa-chevron-right"),
        s.classList.add("fa-chevron-left"),
        t && o.classList.add("slided");
      break;
    case "hide":
      if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
        o.classList.remove("slided");
        const e = document.querySelector(".body-container").getAttribute("activeTopic");
        document.getElementById(e).scrollIntoView()
      }
  }
}
Ilham
  • 1
  • 2
  • Does this answer your question? [How to add attribute to HTML element using javascript](https://stackoverflow.com/questions/27466969/how-to-add-attribute-to-html-element-using-javascript) – Lawrence Cherone Feb 09 '22 at 12:15

1 Answers1

0

You could do :

element.setAttribute("aria-label", element.classList.contains("fa-chevron-left") ? "test1" : "test2");
Tom
  • 4,972
  • 3
  • 10
  • 28
  • I've tried this and it works after pressing an action, it doesn't show the aria-label on load or by default – Ilham Feb 09 '22 at 13:11
  • @Ilham then you should consider asking another question. Neither the title nor the body of your question mentions default value. – Tom Feb 09 '22 at 13:16
  • Sorry I am new to stackoverflow. I've tried your code, it does work, just that I want the "aria-label=test1" when the page is loaded – Ilham Feb 09 '22 at 13:47
  • @Ilham I understood that point. But we can't really help you with the informations you provided in your question. We need more details, we can't guess the structure of your page. On which element is the `aria-label` attribute ? Can't you just set the default value in your HTML code ? That's why I suggested you to ask about it in another question. I recommend you to take a look at the [Tour](https://stackoverflow.com/tour) page and pinned questions of the [Help Center](https://stackoverflow.com/help) – Tom Feb 09 '22 at 13:55
  • The aria-label need to be on this element s = document.querySelector(".slide-btn i.fas"). Unfortunately I can't set the default value in the HTML code. – Ilham Feb 09 '22 at 14:26
  • `s.setAttribute("aria-label", "test1");` – Tom Feb 09 '22 at 14:27