I am currently working on a website where I need to add content dynamically via javascript. I am working with UIKit (https://getuikit.com/docs/slider).
This is what I want to achieve:
<img src="images/photo.jpg" alt="" uk-cover>
What I Already tried:
img = document.createElement("img");
img.ukcover = "";
So how do I add the uk-cover to my img html tag? Thanks!
-
2try img.setAttribute("ukcover", "")Chris Li– Chris Li2018年09月08日 16:52:16 +00:00Commented Sep 8, 2018 at 16:52
-
u have a typo in your comment img.setAttribute("uk-cover", "") worksfor me - post your answer and I'll accept it. Thanks!inxoy– inxoy2018年09月08日 16:55:29 +00:00Commented Sep 8, 2018 at 16:55
-
thanks i posted my answerChris Li– Chris Li2018年09月08日 17:04:40 +00:00Commented Sep 8, 2018 at 17:04
5 Answers 5
You can use Element.setAttribute() that
Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
let img = document.createElement("img");
img.setAttribute('src', 'images/photo.jpg');
img.setAttribute('alt', 'photo');
img.setAttribute('uk-cover', '');
document.body.appendChild(img)
console.log(img);
Please Note: I have set some default text to alt attribute because images with only visual value should have an empty alt attribute set on them.
Comments
to set attribute you can use img.setAttribute("uk-cover", "")
Comments
Dot notation does not work with cases having a hyphen. Use Element.setAttribute
const img = document.createElement("img");
img.setAttribute('uk-cover', "https://picsum.photos/300");
Comments
You can do this with setAttribute(propertyName, value) method.
img = document.createElement("img");
img.setAttribute("ukcover", "");
img.setAttribute("src", "images/photo.jpg");
img.setAttribute("alt", "");
1 Comment
You can use setAttribute() and pass the second argument as a blank string.
img = document.createElement("img");
img.setAttribute('uk-cover','');
img.src = "https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
document.body.appendChild(img);