我正在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.有人能告诉我我做错了什么吗?

推荐答案

您没有看到任何事情发生,因为您正在创建的li没有添加到DOM中.除此之外,你所有的try 都有效.我把代码保存在最简单的下面.

let ul = document.querySelector("ul"); // line I added

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>

Javascript相关问答推荐

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

嵌套异步JavaScript(微任务和macrotask队列)

如何避免页面第一次加载时由于CSS样式通过JavaScript更改而出现闪烁

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

提交链接到AJAX数据结果的表单

如何将数据块添加到d3力有向图中?

如何在Angular拖放组件中同步数组?

扩展类型的联合被解析为基类型

VSCode中出现随机行

无法避免UV:flat的插值:非法使用保留字"

如何用javascript更改元素的宽度和高度?

FileReader()不能处理Firefox和GiB文件

将多个文本框中的输出合并到一个文本框中

处理app.param()中的多个参数

如何使用抽屉屏幕及其子屏幕/组件的上下文?

重新呈现-react -筛选数据过多

更改管线时不渲染组件的react

验证Java脚本函数中的两个变量

JS/css:将数字输入的S函数和可调整大小的元素S函数绑定在一起

如何在Flat Pickr中更改取消选中日期的 colored颜色