JavaScript Add Style to Element

A significant capability of JavaScript is its ability to alter the styles of elements within a webpage. By utilizing JavaScript, you can uphold a dynamic design aesthetic by adjusting the style of an element in response to user input or actions. This article will guide you through the process of adding and modifying the styles of HTML elements with JavaScript.

1. Accessing Elements

Prior to applying any styles, it is essential to obtain the HTML element, which you can do by referencing it. In JavaScript, there are several approaches to select elements, utilizing various methods:

a) document.getElementById:

The function document.getElementById is a native JavaScript method utilized to select and interact with an HTML element that possesses a distinct id. This method ranks among the most frequently employed techniques within the D.O.M (Document Object Model).

Syntax:

Example

var element = document.getElementById("id");

Code:

HTML:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JTP Example</title>
  </head>
  <body>
    <h1 id="header">Hello, User</h1>
    <button id="changeTextBtn">Change Text</button>

    <script src="https://placehold.co/800x200/3498db/ffffff?text=Banner"></script>
  </body>
</html>

JavaScript:

Example

// select the element by its id or some unique selector.
const headerElement = document.getElementById("header");
const buttonElement = document.getElementById("changeTextBtn");

// When we click the button, change the text of the header
buttonElement.addEventListener("click", function () {
  headerElement.textContent = "Welcome To Example";
});

Output:

After Clicking on button

b) document.querySelector:

The document.querySelector method is a function in JavaScript utilized to search the Document Object Model (DOM) for the initial element that corresponds to a given CSS selector. This method stands out as one of the most versatile and robust options available, as it allows for the selection of elements using any valid CSS selector, which encompasses classes, IDs, attributes, or types of elements.

Syntax:

Example

var element = document.querySelector(selector);

Code:

HTML:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JTP</title>
    <style>
      .highlight {
        color: red;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <h1 id="header">Welcome to our tutorial</h1>
    <p class="info">Hello Yashraj how are you.</p>
    <p class="info">Hello Rohit How are you.</p>
    <button id="highlightBtn">Highlight First Paragraph</button>

    <script src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image"></script>
  </body>
</html>

JavaScript:

Example

// selected the html elements using document.querySelector method
const header = document.querySelector("#header");
const firstParagraph = document.querySelector(".info");
const highlightButton = document.querySelector("#highlightBtn");

// you can use the event listner
highlightButton.addEventListener("click", function () {
  // we have changed the style of the first paragraph
  firstParagraph.classList.add("highlight");

  // when user click on button then header text will changed to this
  header.textContent = "Highlighted First Paragraph!";
});

Output:

After Clicking on button

c) document.querySelectorAll:

The document.querySelectorAll function is a method in JavaScript that retrieves all elements that correspond to a specified CSS selector from the document Object Model (DOM). In contrast to document.querySelector, which yields only the initial match, document.querySelectorAll produces a NodeList containing every element that fulfills the selection criteria.

Syntax:

Example

var elements = document.querySelectorAll(selector);

Code:

HTML:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JTP</title>
    <style>
      .highlight {
        color: green;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <h1>Example Site</h1>
    <ul id="itemList">
      <li>Yashraj</li>
      <li>Navven</li>
      <li>Rohit</li>
      <li>Akash</li>
    </ul>
    <button id="highlightBtn">Highlight All Items</button>

    <script src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image"></script>
  </body>
</html>

JavaScript:

Example

// Query all list items and the button
const listItems = document.querySelectorAll("#itemList li");
const highlightButton = document.querySelector("#highlightBtn");

// Event listener to be added on button
highlightButton.addEventListener("click", function () {
  // Loop through each of the selected list items
  listItems.forEach((item) => {
    // Apply the 'highlight' class to every item
    item.classList.add("highlight");
  });
});

Output:

After Clicking on button

2. Modifying Inline Styles

Upon accessing the element, we have the ability to modify its CSS through the style property.

Change Background Color:

The element.style.backgroundColor property is a component of the JavaScript Document Object Model (DOM) that allows for the manipulation or retrieval of the background color of an HTML element. This property is utilized to dynamically assign or retrieve color values, specifically accessing the background-color attribute of a designated element.

Syntax:

Example

// we can set the background color using this property
element.style.backgroundColor = "color";

// it is used to get the background color
var bgColor = element.style.backgroundColor;

Code:

HTML:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Color Changer</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        margin: 0;
        background-color: #f4f4f9;
      }

      #colorBox {
        width: 200px;
        height: 200px;
        border: 2px solid #444;
        border-radius: 10px;
        margin-bottom: 20px;
        transition: background-color 0.3s ease, box-shadow 0.3s ease;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
        font-weight: bold;
        color: #fff;
      }

      #colorBox:empty {
        color: #555;
        background-color: #e0e0e0;
      }

      button {
        padding: 10px 20px;
        margin: 5px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 1rem;
        font-weight: bold;
        color: #fff;
        background-color: #555;
        transition: background-color 0.3s ease, transform 0.2s ease;
      }

      button:hover {
        background-color: #333;
        transform: scale(1.05);
      }

      #redBtn {
        background-color: #e74c3c;
      }

      #redBtn:hover {
        background-color: #c0392b;
      }

      #greenBtn {
        background-color: #2ecc71;
      }

      #greenBtn:hover {
        background-color: #27ae60;
      }

      #blueBtn {
        background-color: #3498db;
      }

      #blueBtn:hover {
        background-color: #2980b9;
      }
    </style>
  </head>
  <body>
    <div id="colorBox">No Color</div>
    <button id="redBtn">Red</button>
    <button id="greenBtn">Green</button>
    <button id="blueBtn">Blue</button>

    <script src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image"></script>
  </body>
</html>

JavaScript:

Example

// Query all list items and the button
const colorBox = document.getElementById("colorBox");
const redButton = document.getElementById("redBtn");
const greenButton = document.getElementById("greenBtn");
const blueButton = document.getElementById("blueBtn");

// Event listener to be added on button so that we can change background color
redButton.addEventListener("click", () => {
  colorBox.style.backgroundColor = "red";
  colorBox.textContent = "Red";
});

greenButton.addEventListener("click", () => {
  colorBox.style.backgroundColor = "green";
  colorBox.textContent = "Green";
});

blueButton.addEventListener("click", () => {
  colorBox.style.backgroundColor = "blue";
  colorBox.textContent = "Blue";
});

Output:

After Clicking on button

Conclusion

Applying Styles to Elements with JavaScript

From inline styling to the manipulation of CSS classes, the adaptability of JavaScript offers significant control over the styling of your web pages. Combining these methods with event handling and responsiveness can elevate your web development skills to a higher standard.

Input Required

This code uses input(). Please provide values below: