I am building a lightbox, in pure JavaScript. I currently have my images loading via AJAX, but i know it is easier to just have the img data-src attribute being replaced onclick to src.
I however have NO idea how this is done in pure JavaScript, by that i mean, without using any libraries.
Can anyone tell me how this is done?
to sum up: How do i change ex:
<img data-src="URL"/>
to:
<img src="URL"/>
without jQuery.
You can do it like shown below:
var imgEl = document.getElementsByTagName('img');
for (var i=0; i<imgEl.length; i++) {
if(imgEl[i].getAttribute('data-src')) {
imgEl[i].setAttribute('src',imgEl[i].getAttribute('data-src'));
imgEl[i].removeAttribute('data-src'); //use only if you need to remove data-src attribute after setting src
}
}
The above code will fetch all img
tags, check if they have a data-src
attribute and if present, replace it with src
.
Demo Fiddle
Get a handle on the image element, and then set it's src
property, using the value from getAttribute()
.
Plain Javascript doesn't have any helper functions to handle data-*
attributes, it just treats them as any other attribute.
var img = document.getElementById("myimg");
img.src = img.getAttribute("data-src");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With