1

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

6
  • Where do you actually call the pink() function? Commented Jun 5, 2020 at 7:03
  • It would be helpful to all if you posted your css, html, and js. The link you provided expects a username and password. Commented Jun 5, 2020 at 7:03
  • is the background-color: pink not just overruled by other styling? Commented Jun 5, 2020 at 7:06
  • The pink() function is called in the console Commented Jun 5, 2020 at 7:19
  • @GetSet good point, sorry for assuming it was open for everyone to see. I'll write the full code next time :) Commented Jun 5, 2020 at 7:26

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @GalAbra! so you're saying my semi-colon in css was the issue... faceplam

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.