Spex3
    

How JavaScript Interacts with HTML & CSS 🌐πŸ–₯️


    

    

How JavaScript Interacts with HTML & CSS 🌐πŸ–₯️
JavaScript is the glue that connects HTML (structure) and CSS (styling), allowing dynamic and interactive web pages.

1️⃣ JavaScript + HTML: Manipulating Content
JavaScript can add, remove, or modify HTML elements dynamically using the DOM (Document Object Model).

βœ… Example: Change Text Dynamically

 

<!DOCTYPE html>
<html lang="en">
<head>
<title>JS + HTML</title>
</head>
<body>
<h1 id="heading">Hello, World!</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerText = "Hello, JavaScript!";
}
</script>
</body>
</html>


πŸ”Ή How it Works?

document.getElementById("heading") β†’ Selects the <h1> element.

.innerText = "Hello, JavaScript!" β†’ Changes its content.

2️⃣ JavaScript + CSS: Styling & Animations
JavaScript can modify CSS properties and apply styles dynamically.

βœ… Example: Change Background Color on Click

<
<button onclick="changeColor()">Change Background</button>

<script>
function changeColor() {
document.body.style.backgroundColor = "lightblue";
}
</script>

πŸ”Ή How it Works?

document.body.style.backgroundColor = "lightblue"; β†’ Directly modifies the CSS property.


βœ… Adding/Removing CSS Classes

<style>
.highlight { color: red; font-weight: bold; }
</style>

<p id="text">This is a paragraph.</p>
<button onclick="toggleHighlight()">Toggle Highlight</button>

<script>
function toggleHighlight() {
document.getElementById("text").classList.toggle("highlight");
}
</script>


πŸ”Ή How it Works?

.classList.toggle("highlight") β†’ Adds/removes the CSS class dynamically.

3️⃣ Understanding the Browser’s JavaScript Engine πŸš€
Each web browser has a JavaScript engine that executes JS code.
Popular engines include:

V8 Engine β†’ Chrome, Edge, Node.js

SpiderMonkey β†’ Firefox

JavaScriptCore β†’ Safari

How the JS Engine Works?
Parsing β†’ Converts JS code into an Abstract Syntax Tree (AST).

Compilation & Optimization β†’ Converts AST into machine code.

Execution β†’ Runs the optimized code using the browser's event loop.

πŸ”Ή Why is this important?

JS is single-threaded but uses asynchronous execution via the event loop.

Optimized engines (like V8) make JavaScript super fast.

🎯 Summary
Interaction Example
Modify HTML Content document.getElementById("id").innerText = "New Text";
Change CSS Styles element.style.color = "red";
Add/Remove CSS Classes element.classList.toggle("className");
JS Engine Executes Code Converts JS to machine code in browsers


    Date: 2025-03-29 00:00:00.000000