简体   繁体   中英

Adding image to element using appendChild yields error

I have this function running on my window.onload function (so the elements exist before it runs)

var img = new Image();
var button = document.getElementsByClassName('myButtons');

img.onload = function () {
    button.appendChild(img);
};

img.src = 'icons/buttons/fav.png' 

However, when I execute this, I get a return of:

button.appendChild is not a function

additionally, I'd like to add a class on to this image I should note as well that I am not using the <button> tag and am instead using this:

<span><a href="#" class="myButton" id="name">text</a></span>

getElementsByClassName returns acollection , not a single button. A collection is similar to an array, but not quite the same. If you want to loop over the collection using .forEach you can use the spread syntax ... to move the contents from the collection into an array. Using this array you can then loop over each button within it, and then use .innerHTML to add the image to each button.

Additionally, to add an class to the image you can use img.classList.add()

See working example below:

 var img = new Image(); var buttons = [...document.getElementsByClassName('myButton')]; img.src = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a'; img.classList.add('img-btn'); img.onload = function() { buttons.forEach(button => { img.id = button.id + '1'; button.innerHTML += img.outerHTML; }); };
 .img-btn { height: 40px; width: 40px; }
 <span><a href="#" class="myButton" id="name1">Btn 1</a></span> <span><a href="#" class="myButton" id="name2">Btn 2</a></span> <span><a href="#" class="myButton" id="name3">Btn 3</a></span>

Also note, using .appendChild() will "move" the img from button to button, you need to use .innerHTML to append the img to multiple buttons.

That's because document.getElementsByClassName returns of type Array . Array does not have a function named appendChild . You probably should use an index to access the button element, like, button[0].appendChild(img) or use a for statement to loop through all the buttons.

You can add a class to the image like this.

img.classList.add("myImageClass");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM