How to modify html tag with javascript?

Viewed 178

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!

5 Answers

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

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

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

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.

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

Related