Home > Mobile >  Can't change the src of a image with JavaScript
Can't change the src of a image with JavaScript

Time:11-22

Im triying to change the source of a image with a js function but it seems to not work, the function executes on a mounted() of Framework7

This is what i have right now

HTML:

<div>
 <span> <img id="star_1"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_2"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_3"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_4"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_5"  src="../assets/empty_star.png"> </span>
</div>

JS:


setStars(){

 var full_star = '../assets/full_star.svg';

 document.getElementById('star_1').src = full_star;
 document.getElementById('star_2').src = full_star;
 document.getElementById('star_3').src = full_star;
 document.getElementById('star_4').src = full_star;                       
 document.getElementById('star_5').src = full_star;
}

This keeps me the empty stars and i wanna change them depending of a rating, how can i fix it?

Image of what im getting right now

I also tryed to get the document.getElementById in var but still does not work

CodePudding user response:

document.querySelectorAll('.star')
  .forEach(el => el.src = '/assets/full_star.svg'');

CodePudding user response:

You should use IIFE Then



;(function () {
const full_star = '../assets/full_star.svg';
const stars = document.querySelectorAll('.star')
stars.forEach((star) => {
      star.src = full_star

})

}());

CodePudding user response:

It looks like your function isn't called an misses the "function" prefix. The following code works:

var full_star = '../assets/full_star.svg';

setStars();

function setStars(){

 document.getElementById('star_1').src = full_star;
 document.getElementById('star_2').src = full_star;
 document.getElementById('star_3').src = full_star;
 document.getElementById('star_4').src = full_star;                 
 document.getElementById('star_5').src = full_star;
}
<div>
 <span> <img id="star_1"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_2"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_3"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_4"  src="../assets/empty_star.png"> </span>
 <span> <img id="star_5"  src="../assets/empty_star.png"> </span>
</div>

  • Related