I want to make a button to change layout from wide to boxed, from class="container"
to class="container-fluid"
, is it possible to change them by Javascript? If yes, how can i do that?
Asked
Active
Viewed 2.0k times
1

Abay
- 35
- 1
- 1
- 8
-
2Yes, that is definetly possible. – Jonas Wilms Jul 19 '18 at 19:16
-
How can i do that? – Abay Jul 19 '18 at 19:17
-
An event listener, some query selectors and `Element.className` – Jonas Wilms Jul 19 '18 at 19:18
-
It is common. try searching toggling between classes. you will find a lot of samples – jmag Jul 19 '18 at 19:18
-
`var ctr = document.querySelector('.container'); var classnames = ctr.className; ctr.className = ctr.className.replace('container', 'container-fluid')` – tika Jul 19 '18 at 19:26
1 Answers
2
Use document.getElementById("myEle").className
to change the class. The classes in below code simply have the background colors. You can put your own css in place of them.
function changeClass(){
document.getElementById("myEle").className = "container-fluid";
}
<style>
.container{
background: yellow;
}
.container-fluid{
background: red;
}
</style>
<div class="container" id="myEle">Hello World</div>
<button onClick="changeClass()">Change class</button>

Hari Das
- 10,145
- 7
- 62
- 59