GiggleSquid GiggleSquid - 3 months ago 13
HTML Question

Javascript change img src on load

I'm trying to use Javascript to change an

img
src
on load. But what I've got doesn't seem to want to work. Any ideas?

(The difference in the img src is
png
and
svg
)

HTML

<img class="fusion-logo-1x" src="//new.network-data-cabling.co.uk/wp-content/uploads/2016/08/ACCL_Logo.png" width="400">


In
<script>
tag in
<head>


window.onload = function() {
document.getElementsByClassName("fusion-logo-1x").src = "//new.network-data-cabling.co.uk/wp-content/uploads/2016/08/ACCL_Logo.svg";
};


Link to JSfiddle

Answer

Document.getElementsByClassName() returns an array-like object, You need to use index to iterate and access it's properties.

document.getElementsByClassName("fusion-logo-1x")[0].src = "//new.network-data-cabling.co.uk/wp-content/uploads/2016/08/ACCL_Logo.svg";
Comments