3

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!

asked Sep 8, 2018 at 16:51
3
  • 2
    try img.setAttribute("ukcover", "") Commented 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! Commented Sep 8, 2018 at 16:55
  • thanks i posted my answer Commented Sep 8, 2018 at 17:04

5 Answers 5

2

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.

answered Sep 8, 2018 at 17:00
Sign up to request clarification or add additional context in comments.

Comments

1

to set attribute you can use img.setAttribute("uk-cover", "")

answered Sep 8, 2018 at 17:04

Comments

1

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");
answered Sep 8, 2018 at 16:57

Comments

1

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", "");
answered Sep 8, 2018 at 16:53

1 Comment

doesn't work, because its not a tag property - and its also uk-cover not ukcover
1

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

answered Sep 8, 2018 at 16:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.