Search code examples
javascripthtmlclassinnerhtml

How to use innerHTML to change a img with a class


I would like to change the img by using Ajax. But the console says "Cannot set property 'innerHTML' of undefined", and the innerHTML does not work properly. How can I change the img which has a class type?

       var pokeIcon = document.getElementsByClassName("type");
        for(var k=0; k < pokeIcon.length; k++){
            pokeIcon[i].innerHTML = "<img src=\"" + data.images.typeIcon + "\">";
        }

HTML is written below; (there are several elements which hace a class type, and so I cant use id for this.

<img src="icons/normal.jpg" alt="type" class="type"/>

Solution

  • Two issues:

    1. Your loop counter is k, but you're using i in the assignment

    2. To change the src of an image, you change src, you don't use innerHTML

    So:

    var pokeIcon = document.getElementsByClassName("type");
    for(var k=0; k < pokeIcon.length; k++){
        pokeIcon[k].src = data.images.typeIcon;
        // ------^--^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
    

    You question title is

    How to use innerHTML to change a img with a class

    ...so if that's really your question, the answer is: You can't reasonably do that. You'd have to set the innerHTML of the parent element, which would mean destroying and recreating all of its descendant elements (which would remove their event handlers, if they have any).

    You might be able to do it with outerHTML, but src is the best way.