skip to Main Content

I am currently working on a timetable for school. I have about 50 buttons of the same class but with different id´s. is it possible to change the color of a specific Button with a specific id with a function in js?
<button type="button" class="btn" onclick="openPopup1()" id="output1"><strong>+</strong></button> <button type="button" class="btn" onclick="openPopup2()" id="output2"><strong>+</strong></button>

These are two of the Buttons as an Example

i had no ideas how to do it and found nothing after research so i hope you can help me 🙂

3

Answers


  1. What’s wrong with document.getElementById("output1").style.backgroundColor="red"? Essentially sets an inline style on the button.

    Login or Signup to reply.
  2. You can change the background color of a button with JS by accessing the element by Id and setting the style attribute appropriately.

    document.getElementById("headerStore").setAttribute("style", "background-color: red;");
    

    You can do it when the page is loaded, or trigger it with the click of a button. You can also reference specific items by ID with CSS as well.

    Hopefully this helps!

    Login or Signup to reply.
  3. This might be overkill and not what you are looking for. But if you pass this to your onclick function, you can reference that button in the function.

    In my example, I add a class of active to whatever button was clicked and remove active from any other clicked buttons.

    function deactiveBtns(){
      let activeBTNs = document.querySelectorAll(".btn.active");
      activeBTNs.forEach((btn) => {
        btn.classList.remove("active");
      });
    }
    
    function openPopup1(el){
     deactiveBtns();
     el.classList.toggle("active");
    }
    
    function openPopup2(el){
     deactiveBtns();
      el.classList.toggle("active");
    }
    .btn.active{
    background:red;
    }
    <button type="button" class="btn" onclick="openPopup1(this)" id="output1"><strong>+</strong></button> <button type="button" class="btn" onclick="openPopup2(this)" id="output2"><strong>+</strong></button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search