Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change attribute from data-src to src WITHOUT jQuery

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.

like image 376
Kristian Daugaard Avatar asked Oct 12 '13 11:10

Kristian Daugaard


2 Answers

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

like image 127
Harry Avatar answered Sep 21 '22 03:09

Harry


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");
like image 39
MrCode Avatar answered Sep 20 '22 03:09

MrCode