I'm facing issue while changing the source of the image using onclick
. It works when I use getElementById
but not when getElementsByClassName
.
Here's the bin...
<h1>Image swapping</h1>
<img src="http://via.placeholder.com/350x150" class="image_swap"/><br>
<button onclick="document.getElementsByClassName('image_swap').src='http://via.placeholder.com/250x150'">Swap to smaller</button>
<button onclick="document.getElementsByClassName('image_swap').src='http://via.placeholder.com/350x150'">Swap to larger</button>
document.GetElementsByClassName returns a list of elements (since you can have multiple things with the same classname) adjust your code to pick the first one for a simple fix
https://jsbin.com/sevituduxu/1/edit?html,output
<button onclick="document.getElementsByClassName('image_swap')[0].src='http://via.placeholder.com/250x150'">Swap to smaller</button>
<button onclick="document.getElementsByClassName('image_swap')[0].src='http://via.placeholder.com/350x150'">Swap to larger</button>
Adding inline event is clumsy and it is against the separation of concern. Use addEventListener
& add event to each of the button.Secondly document.getElementsByClassName
returns a collection. So have to pass the index to add event to the specific element
document.getElementById('smaller').addEventListener('click', function() { document.getElementsByClassName('image_swap')[0].src = 'http://via.placeholder.com/350x150' }); document.getElementById('larger').addEventListener('click', function() { document.getElementsByClassName('image_swap')[0].src = 'http://via.placeholder.com/250x150' })
<h1>Image swapping</h1> <img src="http://via.placeholder.com/350x150" class="image_swap" /><br> <button id="smaller">Swap to smaller</button> <button id="larger">Swap to larger</button>
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.