🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to CSS Notes
Topic #165

Variables and JavaScript


Change Variables With JavaScript

CSS variables have access to the DOM, which means that you can change them with JavaScript.

Here is an example of how you can create a script to display and change the --primary-bg-color variable from the example used in the previous pages. For now, do not worry if you are not familiar with JavaScript. You can learn more about JavaScript in our JavaScript Tutorial:

Example

  <script>
// Get the root element
var r =
  document.querySelector(':root');

// Function for getting a variable
  value
function myFunction_get() {
  // Get the styles (properties
  and values) for the root
  var rs = getComputedStyle(r);
  //
  Alert the value of the --primary-bg-color variable
  alert("The value
  of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}

// Function for setting a variable value
function myFunction_set() {

  // Set the value of variable --primary-bg-color to another value (in this case
  "green")
  r.style.setProperty('--primary-bg-color', 'green');
}

  </script>

CSS var() Function

Function Description
var() Inserts the value of a CSS variable

Want to go beyond the notes?

Join CodingNow 2.0's CSS course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Variables and JavaScript – FAQs

Quick answers about learning Variables and JavaScript in CSS.

This free note from CodingNow 2.0 explains Variables and JavaScript in CSS — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every CSS topic on CodingNow 2.0, including Variables and JavaScript, is 100% free with no signup required.
With focused practice, most students grasp Variables and JavaScript in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now