Learning how to interact with the webpage is essential in frontend development. Here's how the DOM, events, and forms work in JavaScript:
1๏ธโฃ What is the DOM?
DOM (Document Object Model) is the structure of your web page. JavaScript can access and change content, styles, or elements using the DOM.
<p id="message">Hello!</p>```js
let msg = document.getElementById("message");
msg.textContent = "Welcome!";
โถ๏ธ This selects the paragraph and changes its text to โWelcome!โ
2๏ธโฃ Selecting Elements
js
document.querySelector("h1"); // Selects first <h1>
document.querySelectorAll("li"); // Selects all <li> elements
3๏ธโฃ Changing Content or Style
js
let btn = document.getElementById("btn");
btn.style.color = "red";
btn.textContent = "Clicked!";
4๏ธโฃ Events in JavaScript
You can listen for user actions like clicks or key presses.
html
<button id="btn">Click Me</button>
```
```js
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
โถ๏ธ This shows an alert when the button is clicked.
5๏ธโฃ Handling Forms
html
<form id="myForm">
<input type="text" id="name" />
<button type="submit">Submit</button>
</form>
```
```js
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // Prevents page reload
let name = document.getElementById("name").value;
console.log("Hello, " + name);
});
`โถ๏ธ This handles form submission and prints the entered name in the console without refreshing the page.
๐ก Practice Ideas:
โข Make a button that toggles dark mode
โข Build a form that displays entered data below it
โข Count key presses in a textbox
๐ฌ Tap โค๏ธ for more!