简体   繁体   中英

How can I set the data-src on an img with pure JS?

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

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';

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM