The DocumentObject Model (DOM) is a
programming interface for web documents.
It represents the structure of an HTML document
as a tree of objects.
Developers use the DOM to interact with and
manipulate web pages dynamically.
HTML:
<p id="demo">Hello</p>JavaScript:javascript
Javascript:
document.getElementById("demo").innerText = "Hi there!";
What is DOM?
3.
The consoleobject provides methods for
debugging and interacting with JavaScript
code.
Examples:
console.log("This is a log message.");
console.error("This is an error message.");
console.warn("This is a warning message.");
console.clear(); // Clears the console.
Use these to track outputs, warnings, and errors
while debugging your code.
Console Object Functions
4.
JavaScript providesmultiple methods to access
elements in the DOM:
◦ querySelector: Selects the first matching element.
document.querySelector(".className");
◦ querySelectorAll: Selects all matching elements.
document.querySelectorAll(".className");
◦ getElementById: Selects an element by its ID.
document.getElementById("uniqueId");
◦ getElementsByTagName: Selects elements by their tag name
document.getElementsByTagName("div");
◦ getElementsByClassName: Selects elements by their class
name.
document.getElementsByClassName("className");
Selecting DOM Elements
5.
Node vsElement:
◦ A node is a generic term for all items in the DOM tree (elements, text, comments).
◦ An element is a type of node specifically representing an HTML element.
Changing Attributes & Values:
const element = document.getElementById("demo");
element.setAttribute("class", "highlight");
element.innerText = "Changed text!";
Adding & Removing Elements:
const newDiv = document.createElement("div");
newDiv.innerText = "New Element";
document.body.appendChild(newDiv);
document.body.removeChild(newDiv);
Changing Multiple Elements:
const items = document.querySelectorAll(".list-item");
items.forEach((item) => {
item.style.color = "blue";
});
Understanding Nodes and Elements
6.
Events areactions or occurrences like clicks, keypresses, or page
loads.
Adding Event Listeners:
document.getElementById("button").addEventListener( "click", () => {
alert("Button clicked!");
});
Removing Event Listeners:
const handler = () => alert("Clicked!");
document.getElementById("button").addEventListener("click", handler);
document.getElementById("button").removeEventListener("click", handler);
Waiting for the DOM to Load:
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM fully loaded!");
});
Handling Browser Events
7.
The eventobject gives details about the event.
document.addEventListener("click", (event) => {
console.log(event.type); // Outputs: "click"
console.log(event.target); // Outputs the clicked
element
});
Event Object
8.
Local Storage:
◦Stores data with no expiration.
localStorage.setItem("key", "value");
console.log(localStorage.getItem("key")); // Outputs: value
localStorage.removeItem("key");
Cookies
◦ Small pieces of data with optional expiration.
document.cookie = "username=John;
expires=Fri, 31 Dec 2024 23:59:59 GMT;";
console.log(document.cookie);
Storing Data in the Browser
9.
preventDefault:
◦ Stopsthe default action of an event (e.g., preventing a form from
submitting).
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault();
console.log("Form submission prevented!");
});
stopPropagation:
◦ Prevents an event from propagating to parent elements.
document.getElementById("child").addEventListener("click", (event) => {
event.stopPropagation();
console.log("Event stopped!");
});
Controlling Event Behavior
10.
Request/Response Cycle:
◦Explains how browsers request resources from
servers and receive responses.
REST:
◦ A set of rules for designing APIs, often using HTTP
methods (GET, POST, etc.).
Request/Response Cycle and REST
11.
XHR (XMLHttpRequest):An older way to
send/receive data from servers.
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.json");
xhr.onload = () => console.log(xhr.responseText);
xhr.send();
AJAX: A technique for updating web pages
without reloading.
JSON: A format for sending/receiving
structured data.
◦ { "name": "Ali", "age": 15 }
XHR, AJAX, & JSON: Communicating
with Servers
12.
The FetchAPI simplifies server requests and
works with promises.
fetch("data.json")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Fetch API:Modern Data Fetching
14.
Property Description
onreadystatechange Definesa function to be called when the readyState
property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the
Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")
XMLHttpRequest Object Properties
15.
Method Description
new XMLHttpRequest()Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,psw) Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false
(synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be
sent
XMLHttpRequest Object Methods
16.
AJAX (AsynchronousJavaScript and XML)
enables web pages to communicate with
servers without reloading.
Used for dynamic, real-time updates in
applications like eCommerce, social media, and
weather dashboards.
Consider: Fetch product data from a server
without refreshing the page when a user clicks
on a category.
What is AJAX?
17.
function loadProducts() {
constxhr = new XMLHttpRequest(); // Create an XMLHttpRequest object
xhr.open("GET", "https://api.example.com/products", true); // Prepare a GET request
xhr.onload = function () {
if (xhr.status === 200) { // Check if request was successful
const products = JSON.parse(xhr.responseText); // Parse JSON response
products.forEach(product => {
console.log(`Product: ${product.name}, Price: $${product.price}`);
});
} else {
console.error(`Error: ${xhr.status}`); // Handle HTTP errors
}
};
xhr.onerror = function () {
console.error("Request failed."); // Handle network errors
};
xhr.send(); // Send the request
}
loadProducts();
Cont…
AJAX with JavaScript Using XMLHttpRequest
18.
function fetchProducts() {
fetch("https://api.example.com/products")// Make a GET request
.then(response => {
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`); // Check for errors
}
return response.json(); // Parse the response as JSON
})
.then(products => {
products.forEach(product => {
console.log(`Product: ${product.name}, Price: $${product.price}`);
});
})
.catch(error => {
console.error("Failed to fetch products:", error); // Handle errors
});
}
fetchProducts();
Cont…
AJAX with JavaScript Using Fetch