I'm learning Javascript and as an exercise I want to take a list of text ratings and convert it into star ratings.
There are probably some easier ways and libraries to do this but I wanted to try it with my own code just so I can understand how the code works.
I've mostly stumbled my way to a nearly working solution. However, I keep getting an extra star after going through the loops.
Here is a link to fiddle with the full code... Fiddle
This is my HTML
<div class="container" id="container">
<div class="rating" id="rating">1.2</div>
<div class="rating" id="rating">3.2</div>
<div class="rating" id="rating">4.8</div>
<div class="rating" id="rating">5</div>
<div class="rating" id="rating">2.6</div>
</div>
this is my javascript
I'm basically getting all the ".ratings" elements from the parent "container"
const ratingsContainer = document.getElementById('container');
const ratings = ratingsContainer.getElementsByClassName('rating');
Iterating through them;
In the for loop Im fetching the innerHTML of each ratings div.
const ratingScore = parseFloat(ratings[i].innerHTML).toFixed(1);
Im converting them to decimal numbers because I have to split the rating in order to get the number of full stars needed and the number of fractional stars needed.
Im also calculating the number of empty stars needed.
let emptyStars;
emptyStars = fullStars < 5 ? 5 - fullStars - 1 : 0;
I then create the required elements for the fullstars, the fractional stars and the empty stars through a loop for each that looks something like this...
for (let i = 0; i < fullStars; i++) {
const newstarContainer = document.createElement('div');
newstarContainer.className = 'starContainer';
const starFill = document.createElement('div');
starFill.className = 'starFill';
const starFillImage = document.createElement('img');
starFillImage.src = 'images/star.svg';
const starOutline = document.createElement('div');
starOutline.className = 'starOutline';
const starOutlineImage = document.createElement('img');
starOutlineImage.src = 'images/outline.svg';
const newstarContainerFill = newstarContainer
.appendChild(starFill)
.appendChild(starFillImage);
const newstarContainerOutline = newstarContainer
.appendChild(starOutline)
.appendChild(starOutlineImage);
document
.getElementById('container')
.appendChild(newRatingsContainer)
.appendChild(newstarContainer);
}
I do this for the empty and fractional stars as well.
The fractional stars get a custom width style added to the star image container this cuts off the star.svg image based on the percentage width.
const starFill = document.createElement('div');
starFill.className = 'starFill';
starFill.style.width = `${fractionalStars}%`;
Finally I append everything to the container and remove the original text ratings.
My problem is when the text ratings number is 0 or not existing, I get an extra star. I've tried to play around with the code but I cant seem to figure out why its happening.
Can someone please help me to explain what Im doing wrong.