JavaScript DOM Mastery: Selecting and manipulating DOM elements
Sagar Agarwal
Posted on October 8, 2023
The Document Object Model (DOM) stands as a tree-like representation of an HTML document, affording developers the capability to systematically engage with the configuration, substance, and aesthetic aspects of a webpage. Competence in DOM alteration forms an elemental proficiency for front-end developers, facilitating the development of dynamic and interactive web applications.
Within this discourse, we shall delve into the rudiments of DOM modification, encompassing:
-
- The acquisition of elements through ID, class, and tag nomenclature.
Acquisition of Elements through ID, Class, and Tag Nomination
The retrieval of elements from the DOM primarily transpires through three avenues: by ID, by class, and by tag nomenclature.
Element Retrieval by ID
Procuring an element by its unique identifier involves the utilization of the getElementById()
method. This method takes the element's ID as an argument and bestows a reference to the element, provided it exists. To illustrate, consider the ensuing code snippet, which procures the element bearing the ID my-element
:
const element = document.getElementById('my-element');
Element Retrieval by Class
To amass elements by their class, employ the getElementsByClassName()
method. This function mandates the class denomination as input and returns an array encompassing all elements in the document affiliated with that class. For instance, the following code assembles all elements ascribed to the class my-class
:
const elements = document.getElementsByClassName('my-class');
Element Retrieval by Tag Nomenclature
To secure elements via tag nomenclature, employ the getElementsByTagName()
method. This method necessitates the tag denomination as input and presents an array enlisting all elements within the document designated by that tag. For instance, the following code accumulates all div
elements in the document:
const elements = document.getElementsByTagName('div');
DOM Hierarchy Traversal
Once in possession of an element reference, it becomes plausible to navigate the DOM hierarchy and access other elements. The DOM hierarchy maintains a hierarchical structure, wherein each element possesses parent and offspring elements. The ensuing attributes facilitate navigation:
parentNode
: Affords the parent element of the extant element.childNodes
: Yields an array delineating all offspring elements affiliated with the current element.firstChild
: Discloses the foremost offspring element of the existing element.lastChild
: Reveals the terminal offspring element of the present element.nextSibling
: Presents the subsequent sibling element to the extant element.previousSibling
: Unveils the precedent sibling element to the prevailing element.
For example, the subsequent code extracts the parent element of the element sporting the ID my-element
:
const parentElement = document.getElementById('my-element').parentNode;
Additionally, the ensuing code procures all offspring elements of the element designated by the ID my-element
:
const childElements = document.getElementById('my-element').childNodes;
Establishment, Deletion, and Alteration of Elements
The creation of a fresh element calls for the implementation of the createElement()
method. This function demands the tag name of the desired element as its parameter and delivers a reference to the novel element. For instance, the subsequent code generates a new div
element:
const element = document.createElement('div');
To expunge an element from the DOM, the removeChildthe
the method proves invaluable. This method stipulates the element earmarked for removal as its argument and expels it from its parent element. Witness, for instance, the ensuing code obliterating the element with the ID my-element
from the DOM:
document.removeChild(document.getElementById('my-element'));
For the purpose of effecting alterations upon an element, it is permissible to configure its attributes and properties. The ensuing code, for instance, ascribes the innerHTML
property of the element bearing the ID my-element
with the text "Hello World":
document.getElementById('my-element').innerHTML = 'Hello World';
Stylization of Elements through CSS
The application of CSS styling to elements can be executed through the utilization of the style
property. This property functions as an object encapsulating the comprehensive gamut of CSS attributes for the element in question. As an illustration, the ensuing code manipulates the backgroundColor
property of the element marked by the ID my-element
, tinting it red:
document.getElementById('my-element').style.backgroundColor = 'red';
Stylization of Elements through CSS: DOM Manipulation Style
DOM manipulation furnishes the capacity to interact methodically with the composition, content, and style of a webpage. This encompasses the aptitude to stylize elements utilizing CSS.
To impose CSS stylization upon an element via DOM manipulation, exploit the style
property linked to the element. The style
property stands as an object encompassing all pertinent CSS attributes for the element.
The syntax for establishing a CSS property upon an element is articulated as follows:
element.style.propertyName = newValue;
Consider the following illustration, wherein the backgroundColor
property of the element assigned the ID my-element
takes on a crimson hue:
const element = document.getElementById('my-element');
element.style.backgroundColor = 'red';
Moreover, DOM manipulation facilitates the simultaneous application of numerous CSS properties to an element. This can be accomplished through the utilization of the Object.assign()
method.
Illustratively, the ensuing code configures the backgroundColor
, color
, and fontSize
properties of the element having the ID my-element
to crimson, ebony, and 20 pixels, respectively:
const element = document.getElementById('my-element');
Object.assign(element.style, {
backgroundColor: 'red',
color: 'black',
fontSize: '20px',
});
DOM manipulation also encompasses the capability to revoke CSS attributes from an element. This task is undertaken by employing the delete
operator.
For instance, contemplate the subsequent code that dispenses with the backgroundColor
property from the element tagged with the ID my-element
:
const element = document.getElementById('my-element');
delete element.style.backgroundColor;
DOM manipulation can be harnessed to fashion CSS stylization of elements in an array of manners. The ensuing are a few paradigms:
DOM manipulation can be harnessed to engender dynamic and interactive web pages. As an instance, it can be employed to alter the style of an element in response to user actions such as hovering or clicking.
DOM manipulation can be enlisted in the development of adaptive webpages capable of accommodating distinct screen dimensions. For instance, it can be utilized to conceal or unveil elements contingent upon screen width.
DOM manipulation can be wielded to construct accessible webpages. By way of illustration, it can be utilized to modify text contrast or button dimensions to enhance accessibility for individuals with disabilities.
The following exemplifies the use of DOM manipulation to adjust the style of an element upon user hover:
const element = document.getElementById('my-element');
element.addEventListener('mouseover', function() {
this.style.backgroundColor = 'red';
});
element.addEventListener('mouseout', function() {
this style.backgroundColor = '';
});
This code effectuates a transformation in the element's background color to crimson when the user hovers over it, subsequently reverting to its original shade when the user withdraws the cursor.
In summation, DOM manipulation constitutes a potent instrument for the application of CSS stylization to elements. By acquiring proficiency in DOM manipulation, one can conjure dynamic, interactive, adaptive, and accessible web pages.
Posted on October 8, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.