Inline Styling with JavaScript

Introduction

Inline styling with JavaScript allows you to dynamically apply CSS styles to HTML elements directly from your script. This is particularly useful for quick fixes or when there is no predefined CSS for newly created elements.

Applying Inline CSS

To apply inline CSS to a DOM element, use the style property on the element and set the desired CSS property and value. Here's an example:

Example: Changing Text Color

HTML:


                <!DOCTYPE html>
                <html>
                    <head>
                        <title>Inline CSS with JavaScript</title>
                    <head>
                    <body>
                        <h1>Changing text color with JS</h1>
                        <ul>
                            <li>Apple</li>
                            <li>Orange</li>
                            <li>Banana</li>
                        </ul>
                        <script src="red-text.js"></script>
                    </body>
                </html>
            

JavaScript (red-text.js):


const redText = () => {
    const fruits = document.getElementsByTagName("li");
    const apple = fruits[0];

    // Apply inline style
    apple.style.color = "red";
};

window.onload = redText;
            

When this script runs, the first <li> element's text will turn red. The updated DOM structure will look like this:


                <!DOCTYPE html>
                <html>
                    <head>
                        <title>Inline CSS with JavaScript</title>
                    <head>
                    <body>
                        <h1>Changing text color with JS</h1>
                        <ul>
                            <li  style="color: red;">Apple</li>
                            <li>Orange</li>
                            <li>Banana</li>
                        </ul>
                        <script src="red-text.js"></script>
                    </body>
                </html>
         
            

Steps to Apply Inline Styles

  1. Select the element: Use a method like getElementById, getElementsByTagName, or querySelector to target the desired element.
  2. Access the style property: Use the style property on the selected element to access its inline styles.
  3. Set the CSS property: Assign a value to the desired CSS property (e.g., color, backgroundColor, etc.).

Real-World Applications

Inline styling can be used for:

What You Learned

In this guide, you learned how to:

These skills enable you to make quick, dynamic changes to your web applications.