0

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>

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

-1

you can use 1) Element.style = "..." or 2) Element.classList.add("...")

to

  1. overwrite the css with the style attribute
  2. add a class to the element to have it use a predefined styling. (note that elements can have multiple classes)

2 Comments

Setting the style properly doesn't make sense given that the question is specifically about the active class.
Setting Element.class won't do anything. That isn't what the property is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.