etienne-bourganel
etienne-bourganel

Reputation: 23

CSS class applied but style not showing when called from vanilla JS function

I am trying to add a css class to an element in my JS script to change its style through a function but cannot figure out why it does not work.

In the example below, the container I create gets the correct class .container and the appropriate style. Then the function called pink() does add the correct class but the according style

background-color: "pink";

is not applied when called from the console.

Does anyone see what I am missing? Please note I want to learn first with plain vanilla JS.

https://repl.it/join/mtnjkrmj-etiennebrgnl

Upvotes: 1

Views: 1072

Answers (1)

GalAbra
GalAbra

Reputation: 5148

First of all, you need to actually call the pink() function for it to do its magic :)

Secondly, you had semicolons in your CSS file that prevented the classes below container to be read.

Here's a fixed version of your code:

const container = document.querySelector("#container");
container.classList.add("container");


function createCell() {
    const cell = document.createElement("div");
    container.appendChild(cell);
    cell.classList.add("cell");
    return cell.classList;
};

function pink(){
    container.classList.add("pink");
    return container;
};

pink();
.container {
    display: grid;
    width: 500px;
    height: 500px;
    border-style: solid;
    border-width: 1px;
    background-color: grey;
}

.cell {
    background-color: cyan;
}

.pink {
    background-color: pink;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>rclass-test</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="container" class="container"></div>
    
    <script src="script.js"></script>
  </body>
</html>

Upvotes: 1

Related Questions