Convention for representing and interacting with objects in HTML, XHTML and XML documents.
The Document Object Model (DOM) is a crucial aspect of web development, as it allows us to interact with the webpage in real-time. One of the most common tasks when working with the DOM is selecting and manipulating elements. This article will guide you through the process of selecting elements using different methods, understanding NodeList and HTMLCollection, changing element content, manipulating element attributes, and creating, inserting, and deleting elements.
There are several ways to select elements in the DOM:
getElementById
: This method allows you to select an element by its id
attribute. For example, document.getElementById('myId')
would select the element with the id of 'myId'.
querySelector
: This method allows you to select an element using any CSS selector. For example, document.querySelector('.myClass')
would select the first element with the class of 'myClass'.
querySelectorAll
: Similar to querySelector
, but instead of returning the first match, it returns all matches as a NodeList.
getElementsByClassName
and getElementsByTagName
: These methods return a live HTMLCollection of elements with the specified class name or tag name.
When you select multiple elements (like with querySelectorAll
, getElementsByClassName
, or getElementsByTagName
), you get a NodeList or an HTMLCollection. These are array-like objects that contain a list of nodes. You can loop over them using a for
loop or forEach
(only for NodeList).
You can change the content of an element using the innerHTML
and textContent
properties. innerHTML
returns or sets the HTML content (inner HTML) of an element. textContent
returns or sets the text content of a node and its descendants.
You can get, set, and remove attributes (like id
, class
, src
, etc.) using the getAttribute
, setAttribute
, and removeAttribute
methods.
You can create new elements using the createElement
method, and then add them to the DOM using appendChild
or insertBefore
. To remove an element, you can use the removeChild
method.
In conclusion, understanding how to select and manipulate elements in the DOM is a fundamental skill in JavaScript programming. It allows you to create dynamic and interactive webpages, where content can be changed, added, or removed in response to user actions.