Learn Dynamic HTML With JS
Lesson 1 - HTML JS Relationship
Lesson 3 - Browser BOM
Lesson 4 - Basic Interaction
Lesson 5 - Manipulating CSS
Lesson 6 - HTTP Requests
Lesson 7 - Form Handling
DOM manipulation enables you to update content dynamically without refreshing the entire page, thereby enhancing user experience and performance.
This capability allows you to directly alter the Document Object Model (DOM), creating interactive interfaces, responding to user inputs, and updating the visual presentation of web applications in real-time. These features are crucial for modern, responsive web applications where user interaction and feedback play a pivotal role.
DOM methods are functions that facilitate access to and manipulation of HTML DOM elements. Below are some commonly used methods:
getElementById()
: Selects an HTML element by its ID.const element = document.getElementById('myId');
getElementsByClassName()
: Selects HTML elements by their class name.const elements = document.getElementsByClassName('myClass');
getElementsByTagName()
: Selects HTML elements by their tag name.const elements = document.getElementsByTagName('h1');
querySelector()
: Selects the first element that matches a CSS selector.const element = document.querySelector('.myClass');
querySelectorAll()
: Selects all elements that match a CSS selector. Returns a NodeList.const elements = document.querySelectorAll('p');
createElement()
: Creates a new element.const newElement = document.createElement('div');
Let's see how we can use these methods:
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1 id="heading">This is a heading</h1> </body> <script> const element = document.getElementById('heading'); alert(element.innerHTML); </script> </html>
In this example, we selected an HTML element with the ID heading
and displayed its content using element.innerHTML
.