JSFiddle - React, Tailwind, and code Playground
by btipling
HTML
<div id="shelf" class="container">
<div class="iPhone6 smartphone">iPhone 6</div>
<div class="galaxyS5 smartphone">Galaxy S5</div>
<div class="motoX smartphone">Moto X</div>
<div class="stylus accessory">stylus</div>
<div class="case accessory">case</div>
</div>
<div id="shoppingCart" class="container"></div>
<div id="total" class="container">$0</div>
CSS
.container {
padding: 5px;
margin: 5px;
float: left;
width: 150px;
border: 1px solid gray;
}
.container::before {
color: gray;
font-weight: bold;
text-decoration: underline;
display: inline-block;
padding: 5px;
}
#shoppingCart::before {
content: "shopping cart";
}
#shelf::before {
content: "shelf";
}
#total::before {
content: "total:";
}
JavaScript
var prices, shoppingCart = new WeakMap();
prices = new Map([
["smartphone", new Map([
["iPhone6", 610],
["galaxyS5", 650],
["motoX", 179],
])],
["accessory", new Map([
["stylus", 20],
["case", 40],
])],
]);
function getProductFromShelf(type) {
var productEl, clone, price;
productEl = document.getElementById("shelf").querySelector(`.${type}`);
price = prices.get(productEl.classList[1]).get(type);
clone = productEl.cloneNode(true);
document.getElementById("shoppingCart").appendChild(clone);
shoppingCart.set(clone, price);
}
function printTotal() {
var products, total = 0;
products = document.getElementById("shoppingCart")
.querySelectorAll("div");
for (product of products) {
total += shoppingCart.get(product);
}
document.getElementById("total").textContent = `$${total}`;
}
getProductFromShelf("iPhone6");
getProductFromShelf("motoX");
getProductFromShelf("case");
printTotal();