如何使用javascript修改html标签?

时间:2018-09-08 16:51:12

标签: javascript html attributes tags

我目前在一个网站上工作,我需要通过javascript动态添加内容。我正在使用UIKit(https://getuikit.com/docs/slider)。

这是我想要实现的:

<img src="images/photo.jpg" alt="" uk-cover>

我已经尝试过的:

img = document.createElement("img");
img.ukcover = "";

那么如何将uk-cover添加到我的img html标签中? 谢谢!

5 个答案:

答案 0 :(得分:1)

您可以使用setAttribute(propertyName, value)方法执行此操作。

img = document.createElement("img");
img.setAttribute("ukcover", "");
img.setAttribute("src", "images/photo.jpg");
img.setAttribute("alt", "");

答案 1 :(得分:1)

点符号不适用于带有连字符的情况。使用Element.setAttribute

const img = document.createElement("img");
img.setAttribute('uk-cover', "https://picsum.photos/300");

答案 2 :(得分:1)

您可以使用setAttribute()并将第二个参数作为空白字符串传递。

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

答案 3 :(得分:1)

您可以使用Element.setAttribute()

  

设置指定元素上的属性的值。如果属性已经存在,则更新值;否则,将添加具有指定名称和值的新属性。

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

请注意:我已将一些默认文本设置为alt属性,因为仅具有视觉值的图像应在其上设置一个空的alt属性。

答案 4 :(得分:1)

要设置属性,可以使用img.setAttribute(“ uk-cover”,“”)