Reputation:
I was trying to manipulate the css when clicking on button using javascript . I want to just make a single button active the one which is recently clicked.
I am able to make it active but somehow i am not able to remove active for other which is not selected
here is what i tried in js
const myFunction = (event) => {
const clickedElem = event.target
const allBtns = document.querySelectorAll('.btn.lightblue')
allBtns.forEach(btn => btn.classList.remove('.btn.lightblue.active'))
clickedElem.classList.add('active')
}
<p>
<button onclick="myFunction(event)" class="btn lightblue">XASD</button>
<button onclick="myFunction(event)" class="btn lightblue">QWER</button>
<button onclick="myFunction(event)" class="btn lightblue">ASDF</button>
<button onclick="myFunction(event)" class="btn lightblue">ZXCV</button>
</p>
Upvotes: 0
Views: 92
Reputation: 564
you can use 1) Element.style = "..." or 2) Element.classList.add("...")
to
Upvotes: -1
Reputation: 10204
When using remove
function on btn.classList.remove
, pls put className
only.
const myFunction = (event) => {
const clickedElem = event.target
const allBtns = document.querySelectorAll('.btn.lightblue')
allBtns.forEach(btn => btn.classList.remove('active'))
clickedElem.classList.add('active')
}
.active {
background: red;
}
<p>
<button onclick="myFunction(event)" class="btn lightblue">XASD</button>
<button onclick="myFunction(event)" class="btn lightblue">QWER</button>
<button onclick="myFunction(event)" class="btn lightblue">ASDF</button>
<button onclick="myFunction(event)" class="btn lightblue">ZXCV</button>
</p>
Upvotes: 0
Reputation: 944530
Look at the definition of the remove
method:
tokenList.remove(token1[, token2[, ...tokenN]]);
It takes each class that you want to remove as a separate argument (strings with one class name in each).
It doesn't take a single argument with a CSS selector.
… and you probably only want to remove the active
class anyway, not btn
or lightblue
.
Upvotes: 3