I have a shopping cart icon from FontAwesome in which I want to assign the sum of items selected from inputs. I've added the number of items using a JavaScript function but I can't manage to show this number into the icon content.
The content value of the icon is taken from the HTML attribute value=""
as specified in the CSS content:attr(value)
.
How can I modify it to be the value of the JavaScript variable totalQty
?
I used document.getElementsByClassName("badge").value = totalQty;
but it doesn't work.
Here is my code:
.badge:after {
content: attr(value);
font-size: 12px;
color: #fff;
background: red;
border-radius: 50%;
padding: 0 5px;
position: relative;
left: -8px;
top: -10px;
opacity: 0.9;
}
<i id="card-qty" value=""></i>
CodePudding user response:
You can do it with js by targeting the ID instead of the class and do it like this:
var totalQty = 5;
var elementVar = document.getElementById("card-qty");
elementVar.setAttribute("value", totalQty);
So here it is working.
var totalQty = 5;
var elementVar = document.getElementById("card-qty");
elementVar.setAttribute("value", totalQty);
.badge:after {
content: attr(value);
font-size: 12px;
color: #fff;
background: red;
border-radius: 50%;
padding: 0 5px;
position: relative;
left: -8px;
top: -10px;
opacity: 0.9;
}
<i id="card-qty" value=""></i>
EDIT: If you are set on getting the elements by class instead of ID you can use this js code:
var totalQty = 5;
const elementVar = document.getElementsByClassName("badge");
let index = 0;
while (index < elementVar.length) {
elementVar[index].setAttribute("value", totalQty);
index
}
Here it is working:
var totalQty = 5;
const elementVar = document.getElementsByClassName("badge");
let index = 0;
while (index < elementVar.length) {
elementVar[index].setAttribute("value", totalQty);
index
}
.badge:after {
content: attr(value);
font-size: 12px;
color: #fff;
background: red;
border-radius: 50%;
padding: 0 5px;
position: relative;
left: -8px;
top: -10px;
opacity: 0.9;
}
<i id="card-qty" value=""></i>