[英]create element in js then apply style in another css file
const produits=document.getElementById("produit");
let firstDiv = document.createElement("div");
produits.appendChild(firstDiv);
let secondDiv=document.createElement("div");
firstDiv.appendChild(secondDiv);
secondDiv.setAttribute("className","deux");
我在 js 中創建元素然后給它類名 (deux) 然后在 .css 文件 (.deux) 中調用它並嘗試在文件中應用樣式但它沒有工作即使兩個文件都連接到 html 文件
你的錯誤實際上很簡單。 您設置屬性className
而不是僅使用class
。
這是一個帶有工作示例的JsFiddle 。
要在創建元素時在 JS 中添加一個 class,請執行以下操作:
let secondDiv=document.createElement("div");
firstDiv.appendChild(secondDiv);
secondDiv.classList.add("deux");
希望這對你有幫助。
這個文件index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<title>Make element using JS</title>
</head>
<body>
<div id="produit"></div>
<script>
const produits=document.getElementById("produit");
let firstDiv = document.createElement("div");
produits.appendChild(firstDiv);
let secondDiv=document.createElement("div");
secondDiv.innerHTML = "This content class deux"
firstDiv.appendChild(secondDiv);
secondDiv.setAttribute("class","deux");
</script>
</body>
</html>
此文件樣式.css
.deux{
color: red;
}
在第二個 div 中設置 class 屬性時,您的代碼只有錯誤,將className更改為class
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.