2

I would like to set a data-src attribute on an img I am creating with JS.

Why does this not work?

const image = document.createElement('img');
image.className = 'restaurant-img';
image.src = '/img/1.jpg';
image.data-src = DBHelper.imageUrlForRestaurant(restaurant);
li.append(image);

IDE says: Must be lvalue

So I cannot assign it.

How else can I set the data-src on an img then from pure JavaScript (no jQuery);

SLLegendre
  • 680
  • 6
  • 16
  • Possible duplicate of [Set data attribute using JavaScript](https://stackoverflow.com/questions/11286661/set-data-attribute-using-javascript) – Heretic Monkey Aug 07 '18 at 20:17

1 Answers1

6

If you want to set an attribute, you should use setAttribute.

Like this:

const image = document.createElement('img');
image.className = 'restaurant-img';
image.src = '/img/1.jpg';
image.setAttribute('data-src', 'foobar');
document.body.appendChild(image);
console.log(image.outerHTML);

If you wanted to set the element's property name of data-src, you would have to use bracket notation, because - is an illegal character in dot notation:

image['data-src'] = 'foobar';
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320