Home > database >  create element in js then apply style in another css file
create element in js then apply style in another css file

Time:11-25

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");

i created element in js then gave it classname (deux) then called it in .css file (.deux) and tried applying style on it in the file but it didn't work even though both files're connected to html file

CodePudding user response:

Your error is quite simple actually. You set the attribute className instead of just using just class.

Here is a JsFiddle with a working example.

CodePudding user response:

To add a class in JS when creating an element, do like this :

let secondDiv=document.createElement("div");
firstDiv.appendChild(secondDiv);
secondDiv.classList.add("deux");

Hope this helps you.

CodePudding user response:

This file 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>

This file style.css

.deux{
    color: red;
}

Your code is only wrong when setting the class attribute in the second div, change className to class

  • Related