javascript interact with css code example

Example 1: javascript modify css

//Pure JavaScript DOM
var el = document.getElementById("elementID");
el.style.css-property = "cssattribute";

//When doing A CSS property that have multiple words, its typed differently
//Instead of spaces or dashes, use camelCase
//Example:
el.style.backgroundColor = "blue";

//Make sure before using jQuery, link the jQuery library to your code
//JavaScript with jQuery
//jQuery can use CSS property to fid=nd an element
$("#elementID").css("css-property", "css-attribute");

//On jQuery, the CSS property is typed like normal CSS property
//Example: 
$("#elementID").css("background-color", "blue");

//If you want multiple property for jQuery, you can stack them on one code
//instead of typing each attribute
//Example: 
$("#elementID").css({"css-property": "css-attribute", "css-property": "css-attribute"});

//you can also make them nice by adding line breaks
//Example: 
$("#elementID").css({
  "css-property": "css-attribute",
  "css-property": "css-attribute"});
//You can add as much CSS property and attribute as you want
//just make sure, always end it with a comma before adding another one
//the last property doesn't need a comma

Example 2: change color of css in js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change the Background Color with JavaScript</title>
<script>
    // Function to change webpage background color
    function changeBodyBg(color){
        document.body.style.background = color;
    }
    
    // Function to change heading background color
    function changeHeadingBg(color){
        document.getElementById("heading").style.background = color;
    }
</script>
</head>
<body>
    <h1 id="heading">This is a heading</h1>
    <p>This is a paragraph of text.</p>
    <hr>
    <div>
        <label>Change Webpage Background To:</label>
        <button type="button" onclick="changeBodyBg('yellow');">Yellow</button>
        <button type="button" onclick="changeBodyBg('lime');">Lime</button>
        <button type="button" onclick="changeBodyBg('orange');">Orange</button>
    </div>
    <br>
    <div>
        <label>Change Heading Background To:</label>
        <button type="button" onclick="changeHeadingBg('red');">Red</button>
        <button type="button" onclick="changeHeadingBg('green');">Green</button>
        <button type="button" onclick="changeHeadingBg('blue');">Blue</button>
    </div>
</body>
</html>

Tags:

Html Example