Javascript with DOM

Javascript with DOM

JavaScript with DOM (Document Object Model) 

The Document Object Model (DOM) allows JavaScript to access, modify, and manipulate HTML and CSS dynamically.

1️⃣ Accessing Elements in the DOM

JavaScript provides several methods to select elements.

📌 getElementById() – Select by ID

let element = document.getElementById("myDiv"); console.log(element.innerHTML);

🔹 Selects an element using its id.

📌 getElementsByClassName() – Select by Class

let items = document.getElementsByClassName("myClass"); console.log(items[0].innerText);

🔹 Returns a collection (HTMLCollection) of elements.

📌 getElementsByTagName() – Select by Tag Name

let paragraphs = document.getElementsByTagName("p"); console.log(paragraphs[0].innerHTML);

🔹 Selects all elements of a given tag name.

📌 querySelector() – Select the First Match

let firstParagraph = document.querySelector("p"); console.log(firstParagraph.innerText);

🔹 Selects the first matching element using CSS selectors.

📌 querySelectorAll() – Select All Matches

let allParagraphs = document.querySelectorAll("p"); console.log(allParagraphs.length);

🔹 Returns a NodeList (array-like) of all matching elements.

2️⃣ Changing & Modifying Elements

📌 Changing HTML Content (innerHTML)

document.getElementById("myDiv").innerHTML = "<b>New Content</b>";

📌 Changing Text (innerText / textContent)

document.getElementById("myDiv").innerText = "Hello World!"; document.getElementById("myDiv").textContent = "Hello World!";

📌 Changing CSS Styles (style property)

document.getElementById("myDiv").style.color = "blue"; document.getElementById("myDiv").style.fontSize = "20px";

📌 Changing Attributes (setAttribute)

document.getElementById("myLink").setAttribute("href", "https://google.com");

📌 Getting Attributes (getAttribute)

let link = document.getElementById("myLink").getAttribute("href"); console.log(link);

3️⃣ Adding & Removing Elements

📌 Creating a New Element

let newElement = document.createElement("p"); newElement.innerText = "This is a new paragraph."; document.body.appendChild(newElement);

📌 Removing an Element

let element = document.getElementById("myDiv"); element.remove();

📌 Replacing an Element

let newPara = document.createElement("p"); newPara.innerText = "This is a replacement!"; let oldElement = document.getElementById("myDiv"); oldElement.replaceWith(newPara);

4️⃣ Handling Events in JavaScript

Events allow us to execute JavaScript when users interact with the webpage.

📌 Example: Click Event

document.getElementById("myButton").addEventListener("click", function() { alert("Button Clicked!"); });

📌 Mouse Events

document.getElementById("myDiv").addEventListener("mouseover", function() { this.style.backgroundColor = "yellow"; });

📌 Keyboard Events

document.addEventListener("keydown", function(event) { console.log("Key Pressed:", event.key); });

5️⃣ Traversing the DOM

You can navigate between elements using parent-child relationships.

📌 Parent Node

console.log(document.getElementById("myDiv").parentNode);

📌 Child Nodes

let parent = document.getElementById("parentDiv"); console.log(parent.children); // Returns all child elements

📌 Sibling Nodes

let element = document.getElementById("myDiv"); console.log(element.nextElementSibling); // Next element console.log(element.previousElementSibling); // Previous element

6️⃣ Full Example: JavaScript DOM in Action

<!DOCTYPE html> <html lang="en"> <head> <title>DOM Example</title> <style> #myDiv { padding: 20px; border: 1px solid black; } </style> </head> <body> <div id="myDiv">Hello World!</div> <button id="myButton">Click Me</button> <script> document.getElementById("myButton").addEventListener("click", function() { let div = document.getElementById("myDiv"); div.innerText = "You clicked the button!"; div.style.color = "red"; }); </script> </body> </html>

Summary

MethodDescription
getElementById(id)Selects an element by ID.
getElementsByClassName(class)Selects elements by class (HTMLCollection).
getElementsByTagName(tag)Selects elements by tag name (HTMLCollection).
querySelector(css)Selects the first matching element.
querySelectorAll(css)Selects all matching elements (NodeList).
innerHTMLChanges HTML content inside an element.
innerText / textContentChanges the text inside an element.
style.propertyChanges CSS styles dynamically.
setAttribute(name, value)Sets an attribute of an element.
addEventListener(event, function)Listens for user events (click, hover, keypress, etc.).

Now you’re ready to manipulate the DOM like a pro! 🚀
Let me know if you have any questions! 😃

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close