user11877626
user11877626

Reputation:

How to manipulate css using javascript?

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

Answers (3)

Torge Rosendahl
Torge Rosendahl

Reputation: 564

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)

Upvotes: -1

Derek Wang
Derek Wang

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

Quentin
Quentin

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

Related Questions