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 a collection, 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.