JavaScript,如何添加css属性到一个新创建的元素?



我试图将我的元素添加到无序列表。但在创建元素的过程中,我还想将其链接到一个具有css属性的外部css文件。我参考了以下堆栈溢出解决方案:使用JavaScript为元素添加CSS属性

let a = document.getElementsByTagName('ul')[0];
let myelement = document.createElement('li');
// tried this first 
myelement.style.border = '2px solid red';
myelement.style.backgroundColor = 'rgb(255, 125, 115)';
let mytext = document.createTextNode('Green Onions');

// second method I tried to link with the external CSS file which I actually want
myelement.setAttribute("class","myclass")

// third method I tried to link with the external CSS file which I actually want
let myattrib = document.createAttribute('class');
myattrib.value = "myclass"
myelement.setAttributeNode(myattrib)

a.appendChild(mytext)
.myclass {
color: brown;
text-emphasis-color:blue;
}
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 id="header">Last King</h1>
<h2>Buy Groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em>figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic sugar</li>
</ul>
<script src="index.js">
</script>
</body>
</html>

这些方法都不能添加具有CSS属性的新元素,尽管使用第一个方法我可以添加文本节点Green Onions。这是我第一次学习JS。有人能告诉我我做错了什么吗?

您没有看到任何事情发生,因为您正在创建的li没有被添加到DOM中。除此之外,你所有的尝试都成功了。我把代码保留在最简单的代码下面。

let ul = document.querySelector("ul"); // line I changed
let myelement = document.createElement("li");
let mytext = document.createTextNode("Green Onions");
myelement.appendChild(mytext); // line I added
myelement.setAttribute("class", "myclass");
ul.appendChild(myelement); // line I added
.myclass {
color: brown;
text-emphasis-color: blue;
}
<h1 id="header">Last King</h1>
<h2>Buy Groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em>figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic sugar</li>
</ul>

您可以使用两个属性,classListclassName。按照我的理解,您希望实现以下目标:

<li style="border:...;background-color:..." class="myclass">

你已经创建了元素并添加了样式,但是现在你不知道如何添加css类myclass,对吗?

let myelement = document.createElement('li');
// method a
myelement.className = 'myclass';
// method b
myelement.classList.add('myclass');

我总是选classList。我发现它的所有方法都比className优雅得多。

相关内容

最新更新