Home > Back-end >  How to switch class between eliment?
How to switch class between eliment?

Time:01-24

I wanna switch class name active between button. That's mean,at a time only one button can be green by clicking. How is it possible by vanila js?

.active{
    background-color:green;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <button>Button1</button>
    <button >Button2</button>
    <button>Button3</button>
</body>
</html>

CodePudding user response:

Try this: First, I added a unique id to each button, so they could be identified in code.

<button id="button1">Button1</button>
<button id="button2" >Button2</button>
<button id="button3">Button3</button>

Then I added a listener to the window’s load event, which gets a the list of buttons whose id starts with “button” and adds a listener to each one’s click event. The click handler is a function named select.

window.addEventListener('load', () => {
    const buttons = document.querySelectorAll('button[id^=button]')
    buttons.forEach(button => {
        button.addEventListener('click', select)
    })
})

The select function uses querySelector to find the currently active button (i.e. the one with the active class), and remove the class from it. Then it adds the active class to the button that was clicked instead.

function select(evt) {
    document.querySelector('.active').classList.remove('active')
    evt.target.classList.add('active')
}
  • Related