Sure! Here's a simple blog-style explanation to help you learn how if
conditions and element selection with document
work in JavaScript. This will help you understand how to check conditions and interact with web elements on a page.
🧠 Learning JavaScript: if
Conditions and the document
Object
When you're learning JavaScript, two things are super important:
-
Making decisions in your code (
if
statements) -
Getting elements from your web page (
document.getElementById
, etc.)
Let’s break these down!
✅ 1. What is an if
condition?
An if
condition lets you run some code only if a certain condition is true.
Example:
let age = 18;
if (age >= 18) {
console.log("You can vote!");
}
How it works:
- JavaScript checks if
age
is greater than or equal to 18. - If that’s true, it runs the code inside
{ }
.
You can also add:
-
else
(if the condition is false) -
else if
(check another condition)
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You are too young.");
}
🌐 2. Using document
to work with web page elements
In web pages, we use JavaScript to read or change things like buttons, text, or input fields.
Example: Get an element
<p id="myText">Hello!</p>
<script>
let element = document.getElementById("myText");
console.log(element.innerText); // Output: Hello!
</script>
Explanation:
-
document
is the whole web page. -
getElementById("myText")
finds the element with that ID. -
innerText
gets the text inside the tag.
👨💻 Combine if
with document
Let’s say you want to show a message only if someone types "admin" in an input box.
<input type="text" id="username" value="admin">
<p id="message"></p>
<script>
let input = document.getElementById("username").value;
if (input === "admin") {
document.getElementById("message").innerText = "Welcome, admin!";
} else {
document.getElementById("message").innerText = "Access denied.";
}
</script>
🎓 Practice Idea
Try this:
- Create an input box and a button.
- When the button is clicked, check if the input is "hello".
- If yes, change the background color of the page.
Let me know if you want help building it!
Would you like this turned into a real working example you can try in your browser?
Top comments (0)