DEV Community

rajeshwari rajeshwari
rajeshwari rajeshwari

Posted on

🧠 Learning JavaScript: if Conditions and the document Object

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:

  1. Making decisions in your code (if statements)
  2. 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!");
}
Enter fullscreen mode Exit fullscreen mode

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.");
}
Enter fullscreen mode Exit fullscreen mode

🌐 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

🎓 Practice Idea

Try this:

  1. Create an input box and a button.
  2. When the button is clicked, check if the input is "hello".
  3. 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)