How to Change CSS Using JavaScript

  • 7 min read
  • December 21, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in an HTML document.

There are three ways CSS can be applied to an HTML document:

  1. Inline – using the style attribute inside HTML elements;
  2. Internal – using a <style> element in the HTML document’s <head>
  3. External – using a <link> element which links to an external CSS file

All three approaches are explored below. Each approach has its advantages and disadvantages, but we’ll explore them in another article.

Two things are required in order to make CSS changes:

  1. An event to trigger the change – This can be a DOM event or a JavaScript event as in the case of setTimeout(). It can also be done with CSS pseudo-classes – more on these below.
  2. A function in charge of making the change -This can change most CSS style elements, with the exception of CSS selectors.

Change CSS using inline styling

The first approach to changing CSS with JavaScript will be to leverage inline styling. Take the following example:

JavaScript

function changeColor(event) {
  const el = event.target;
  el.setAttribute('style', 'color: blue');
}

HTML

<h2 class="h2colored" style="color:red" onclick="changeColor(event)">
  Click to change color
</h2>

CSS

.h2colored {
  cursor: pointer;
}

This code defines a header element(<h2>), an onclick event, and a single stylecursor: pointer. The cursor: pointer style modifies the display of the mouse cursor, which is used to show the mouse’s current position on the screen. Setting the style to pointer causes the cursor to change appearance, making it look like a hand. This can help the user understand that a given element can be interacted with by, for example, clicking on the link.

Note: This style is not necessary for the code to work. The HTML element does not need to have a clear class defined in order for the JavaScript to modify its contents.

Exploring the example in more detail:

The triggering DOM event is onclick, which is defined inside the <h2> element. This event is handled by the changeColor() function.

The changeColor() function receives the DOM event as a parameter, making it very easy to operate on the specific tag that was clicked.

The function declares the variable to hold the element – el – and assigns the event.target value to it. This sets our <h2> element as the active object being modified. Next, the function applies setAttribute() to reset the style attribute of the element. If the style attribute has not been previously defined, setAttribute simply adds it to the element upon completion of execution.

After the click event handler has completed, the <h2> tag will have blue for its color, instead of the red value that was already present. This will be visible when using the browser’s development tools, with the changes persisted to the element upon completion.

Note: Inline CSS is the most specific way to apply styles to an element, and as such this method has precedence over the other two CSS modification options. Inline CSS thus overrides most other CSS declarations.

Change CSS using internal styling

The next approach to changing CSS with JavaScript uses internal styling. Take the following sample code:

JavaScript

function largeFont() {
  const dStyle = document.querySelector('style');
  dStyle.innerHTML = 'p {font-size: 2rem;}';
}

This code modifies the style of all <p> elements in the document, causing them to have large fonts.

This approach depends on having a style element defined in the HTML document’s <head> element. If the style element is not present in the original HTML document, this function will not work and const dStyle will return null. You can work around this by creating the required element in the function itself, before attempting to manipulate the style. An example of properly formatted HTML, with a style element, is provided below:

HTML

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    p {
      font-size: 1.2rem;
    }
  </style>
</head>
<body>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem, culpa. Voluptatem
  </p>
  <button onclick="largeFont()">A+</button>
</body>

The above markdown can be used with the sample function provided above to manipulate the CSS used by the document. There are three important elements to note:

In the <head> element:

In the head element, the <style> tag sets the font size for all <p> elements in the document to 1.2rem.

In the <body> element:

In the body element we define a button. The onclick event handler for this button is the largeFont() function provided above.

The function Script:

The click handler function locates the style element, then changes the HTML itself using the innerHTML command.

Change CSS using external styling

The final way to implement CSS changes is by using external styling. The following example JavaScript is used to do this:

JavaScript

function changeClass(el) {
  el.classList.add('yellowBgc');
}

The above example captures the element to modify in a different manner than what we have seen thus far. The first examples used the event object to capture the styled element. Here, the parameter passed in to the changeClass() function is this. The this pointer in this instance is the element itself – currently the <p> element. See the HTML definition of this handler below for more detail.

This code modifies the element’s class list. By using classList.add() it adds a class to that element – in this case, the class yellowBgc was added to a <p> element. This class value can then be implemented in an external CSS file.

Next, we’ll make some basic modifications to an HTML document to incorporate the external styling that holds the definition of class yellowBgc.

To link an external CSS document into your HTML, add the following element in your page’s <head>:

HTML

<link rel="stylesheet" href="/style/style.css">

This includes the stylesheet /style/style.css in the document. You can change the location specified in the href attribute to point to whichever file location is needed. The contents of style.css are below:

CSS

.yellowBgc {
  background-color: yellow;
}

The above yellowBgc class, when applied to an HTML element, sets the background color to yellow.

We tie the functionality together with the following HTML, in the <body> of the document:

HTML

<body>
  <p class="lorem" onclick="changeClass(this)">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem, culpa. Voluptatem.
  </p>
</body>

This code defines an element – <p>, which has an onclick event handler. This event handler points at our function above and, critically, passes it the this pointer as its sole argument. Using the this pointer allows us to refer directly to the element in our handler code, rather than having to pull the element from the event target.

Change CSS using CSS pseudo-classes

Some CSS selectors point to a certain state of affairs on the webpage (e.g. :hover only comes into effect when the cursor is over the element); or take the state into consideration (e.g. :visited selects all visited links). It is possible to use these states to alter the page’s CSS. For example:

CSS

.blueText:hover {
  color: blue;
}

The above style is used whenever the user hovers the mouse cursor over an element with the class blueText. When the cursor is over the element, the text will turn blue per the style definition. When the cursor leaves the element, the color will be back to its original value.

 

Related Articles:

JavaScript – How to Use setAttribute

JavaScript – How to Use setTimeout

JavaScript – How to Use onfocus

Related Posts

How to Get an Object’s Keys and Values in JavaScript

How to Get an Object’s Keys and Values in JavaScript

In JavaScript, getting the keys and values that comprise an object is very easy. You can retrieve each object’s keys, values, or both combined into an

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement