Javascript - Change element's src in specified element

14,412

getElementsByName returns a list of elements, not a single element, so try:

document.getElementsByName('p'+pos)[0].
    getElementsByTagName("img")[0].src="player.png";
Share:
14,412
Kyrtap
Author by

Kyrtap

Updated on June 14, 2022

Comments

  • Kyrtap
    Kyrtap about 2 years

    In html I have a lot od DIVs with names(yes, names, not IDs) respectively p001, p002, p003... which are like this:

    <div id="pole" name="p001"><img src=""></div>
    <div id="pole" name="p002"><img src=""></div>
    <div id="pole" name="p003"><img src=""></div>
    

    etc...

    In Javascript I have defined variable called 'pos' which contains a number, for now: "284" and a function which should change img src to "player.png". I tried 2 ways and none of these work:

    document.getElementsByName('p'+pos).innerHTML='<img src="player.png">';
    

    and

    document.getElementsByName('p'+pos).getElementsByTagName("img").src="player.png";
    

    How to change img src which is in specified DIV?