簡體   English   中英

JavaScript,如何給新建的元素添加css屬性?

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

我正在嘗試將我的元素添加到無序列表中。 但是在創建元素的過程中,我還想將其鏈接到具有 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>

這些方法都無法添加具有 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">

您已經創建了元素並添加了 styles 但現在您不知道如何添加 css class myclass ,對嗎?

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

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

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

我總是 go 為classList 我發現它的所有方法都比className優雅得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM