JS DOM_NEW
JS DOM_NEW
FORMS
In the world of web development, understanding how to manipulate
the Document Object Model (DOM) with JavaScript is crucial. The
DOM represents the structure of a web page, allowing developers to
interact with and modify its content and layout dynamically.
Mastering DOM manipulation enables you to create interactive and
responsive web applications, enhancing user experience significantly.
JavaScript is the primary language used to manipulate the DOM. It
provides powerful methods and properties to select, modify, and
interact with elements on a web page. Whether you want to change
text content, update styles, or handle user interactions, JavaScript
offers the tools you need.
Exercise 1: Changing Text Content
One of the most common tasks in DOM manipulation is changing the
text content of elements. This exercise will guide you through the
process of selecting an element and updating its text content using
JavaScript.
Step-by-Step Guide
1. Select the Element:
Use document.getElementById(), document.querySelector(), or
other selection methods to target the element you want to
modify.
// Example: Selecting an element with the id "example"
let element = document.getElementById("example");
Methods to Select Elements
A. By ID
Use document.getElementById("id") to select an element with a
specific id.
var element = document.getElementById("myId");
B. By Class Name
Use document.getElementsByClassName("className") to select all
elements with a specific class.
var elements = document.getElementsByClassName("myClass");
C. By Tag Name
Use document.getElementsByTagName("tagName") to select all
elements of a specific tag type.
var elements = document.getElementsByTagName("div");
D. By CSS Selectors
Use document.querySelector("cssSelector") to select the first
element that matches a CSS selector.
var element = document.querySelector(".myClass");
var element = document.querySelector("#myId");
Example Use Case: Select the first element with
class="myClass".
E. By CSS Selectors (Multiple)
Use document.querySelectorAll("cssSelector") to select all elements
matching a CSS selector.
This returns a NodeList.
var elements = document.querySelectorAll(".myClass");
Example Use Case: Select all elements with class="myClass".
2. Update Text Content: Use the textContent or innerHTML property
to change the text inside the selected element.
// Changing the text content of the selected element
element.textContent = "New Text Content";
Example
Suppose you have the following HTML:
<p id="example">Original Text Content</p>
<button id="changeTextButton">Change Text</button>
You can change the text content of the paragraph when the button is
clicked with the following JavaScript:
// Selecting the button element
let button = document.getElementById("changeTextButton");
<script>
// Selecting the input and form elements
let inputElement = document.getElementById("exampleInput");
let form = document.getElementById("exampleForm");