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

JavaScript, how to add css attribute to a newly created element?

我正在尝试将我的元素添加到无序列表中。但是在创建元素的过程中,我还想 link 将其添加到具有 css 属性 的外部 css 文件。我参考了以下 Stack Overflow 解决方案: Add CSS attributes to element with JavaScript.

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>


   

None 这些方法用于添加带有 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 class myclass,对吗?

let myelement = document.createElement('li');

// method a
myelement.className = 'myclass';

// method b
myelement.classList.add('myclass');

我会一直选择 classList. With all its methods I find it much more elegant than className