7

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.

2
  • On what action do you want to change this? Commented Oct 12, 2013 at 11:34
  • Just wanted to make a listner for a click. But i got the answer now below :) Commented Oct 12, 2013 at 11:42

3 Answers 3

14

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

Sign up to request clarification or add additional context in comments.

Comments

7

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");

Comments

2

You can use forEach with querySelectorAll

var imageElements = document.querySelectorAll('img');
   
imageElements.forEach(c=> c.setAttribute('src',c.getAttribute('data-src')));
img{width:100px;}
<img data-src='https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png' />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.