JavaScript is the scripting language that brings interactivity to your websites. One of its most powerful features is the ability to manipulate the DOM (Document Object Model)—essentially the structure of your HTML—using variables.
In this blog, we'll break down:
•What variables are in JavaScript
•How they interact with HTML through the DOM
•Examples of how to use them effectively
🧠 What Are JavaScript Variables?
Variables in JavaScript are used to store data that you can use later in your code. Think of them as labeled containers for values like numbers, strings, or even entire HTML elements.
Declaring Variables
You can declare a variable using:
let name = "John"; // Can be reassigned
const age = 30; // Cannot be reassigned
var city = "Paris"; // Old way, less commonly used now
🌿 Introduction to the DOM
The DOM (Document Object Model) is a tree-like structure created by the browser from your HTML. It lets JavaScript read and manipulate elements on the page.
Here’s a simple HTML example:
<!DOCTYPE html>
JS and DOM
Welcome!
Click Me
In this example, JavaScript can access and change the
element using the DOM.
🛠️ Using Variables to Change the DOM
Let’s write the script.js:
function changeTitle() {
let newTitle = "Hello, JavaScript!"; // Variable storing new text
document.getElementById("title").innerText = newTitle;
}
What’s Happening Here?
•newTitle is a variable storing the new message.
•document.getElementById("title") accesses the
element by its ID.
•innerText = newTitle updates the content of the
.
🔄 Dynamically Changing Styles
You can also use variables to change styles:
function changeColor() {
let color = "blue";
document.getElementById("title").style.color = color;
}
This will change the
text color to blue when the function is called.
🚀 Conclusion
JavaScript variables are fundamental building blocks that allow you to interact with HTML in powerful ways through the DOM. Once you understand how variables and the DOM work together, you can make your websites come alive with dynamic behavior.
Next Step: Try building a simple form or interactive quiz using what you’ve learned. It’s a great way to solidify your understanding!
Top comments (0)