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
- Select the element: Use a method like
getElementById,getElementsByTagName, orquerySelectorto target the desired element. - Access the style property: Use the
styleproperty on the selected element to access its inline styles. - 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:
- Highlighting specific elements based on user interaction.
- Applying temporary styles for debugging purposes.
- Quickly customizing dynamically created elements.
What You Learned
In this guide, you learned how to:
- Select DOM elements using JavaScript methods.
- Apply inline CSS styles dynamically using the
styleproperty. - Understand the structure of inline styles within the DOM.
These skills enable you to make quick, dynamic changes to your web applications.