Set Class with Javascript

by Matthew Day

HTML

<h1>Elderflower</h1>
<div id="content">
  <div class="message">Available: <span id="stock"></span></div>
  <div class="message">Shipping: <span id="shipping"></span></div>
</div>

CSS

.true {
    display: inline-block;
    width: 10px;
    height: 10px;
    background: red;
}

.false {
    display: inline-block;
    width: 10px;
    height: 10px;
    background: blue;
}

JavaScript

// create variables and assign their values
var inStock;
var shipping;
inStock = true;
shipping = false;

// get the element that has an id of stock
var elStock = document.getElementById('stock');
// Set class name with value of inStock variable
elStock.className = inStock;

// get the element that has an id of shipping
var elShip = document.getElementById('shipping');
// Set class name with value of shipping variable
elShip.className = shipping;