我正在try 将我的元素添加到无序列表中.但是在创建元素的过程中,我还想将其链接到具有css属性的外部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属性添加新元素,尽管使用第一个方法,我只能添加文本 node Green Onions
.我是第一次学习JS.有人能告诉我我做错了什么吗?