Mastering DOM: Element Selection

Ukpa Uchechi
7 min readOct 16, 2023

--

To have a dynamic page, that interacts with the user, displays information after a certain time, removes items from the webpage, etc, we must understand how element selection works. Element Selection is a process of selecting elements on an HTML page and manipulating the DOM based on the element selected. It can be to add event listeners, create Elements, remove classes, add styles, and many more.

There are different ways to select an Element from the HTML page:

getElementById

This is a method of the document an object in JavaScript, which allows you to select an HTML element based on its unique id attribute.

Every HTML Element can have a unique id attribute when the id key is specified. getElementById works by searching the entire DOM for an element with a matching id. If a matching element is found, getElementById returns a reference to that Element, which is an instance of the HTMLElement or a more specific subtype of HTMLElement(e.g, HTMLDivElement, HTMLInputElement, etc depending on the type of element being selected). If no match is found, it returns null.

Pros

Efficient: It is one of the most efficient and direct ways to select an element because it leverages the unique identifier.

Specific Targeting: It allows you to specifically target a single element on the page making it ideal for cases where you know the exact ID of the element you want to interact with.

Cons

Requires Unique IDs: IDs must be unique within the document, if you have multiple elements with the same ID, getElementById will only return the first one it encounters.

Usage

const myElement = document.getElementById('myElementId');

if (myElement !== null) {
// Found an element with the ID 'myElementId'
// Perform actions on the element
myElement.textContent = 'Hello, World!';
} else {
// No element found with the ID 'myElementId'
console.log('Element not found');
}

getElementByClassName

This is a method of the document object in JavaScript, which allows you to select HTML elements based on their class names.

Every HTML element can have one or more class names associated with it. getElementByClassName works by searching the entire DOM for elements that have a specific class name. If one or more matching elements are found, getElementByClassName returns a live HTMLCollection of those elements, if no matches are found, it returns an empty collection.

What is an HTMLCollection?, this article is for you https://ukpauchechi1.medium.com/htmlcollection-a1fcfd47609c

Pros

Select Multiple Elements: Unlike getElementById, which selects only one element(since IDs are unique), getElementByClassName can return multiple elements with the same class name.

Efficient for Group Operations: If you want to apply the same operations to multiple elements with the same class, this method provides a straightforward way to do so.

Cons

Returns a Collection: It returns an HTML Collection, which is an array-like object, so you need to loop through it or access elements by index.

Usage

// Assume you have the following HTML structure:
// <div class="myClass">Element 1</div>
// <div class="myClass">Element 2</div>
// <div class="myClass">Element 3</div>

const elementsWithClass = document.getElementsByClassName('myClass');

// elementsWithClass is an HTMLCollection
// It contains all elements with the class 'myClass'
// You can access them using indexes (0, 1, 2, ...)
console.log(elementsWithClass[0].textContent); // Output: "Element 1"
console.log(elementsWithClass[1].textContent); // Output: "Element 2"
console.log(elementsWithClass[2].textContent); // Output: "Element 3"

getElementByTagName

This is a method of the document object in JavaScript, which allows you to select HTML elements based on their tag name.

Every HTML element has a tag name(e.g., div, p, a, etc.), getElementByTagName works by searching the entire DOM for elements that have a specific tag name. If one or more matching elements are found, getElementByTagName returns a live HTMLCollection of those elements. If no matches are found, it returns an empty collection.

Pros

Select Multiple Elements: Like getElementsByClassName, getElementsByTagName can return multiple elements, which is useful when you want to perform the same operation on a group of elements.

Efficient for Group Operations: If you want to apply the same operation to multiple elements with the same tag name, This method allows you to do so.

Cons

Returns a Collection: It returns an HTMLCollection, which is an array-like object, so you need to loop through it or access elements by index.

Potential for Many Elements: Depending on the tag name you use, getElementsByTagName can potentially return a large number of elements, This can have some performance implications.

Usage

// Assume you have the following HTML structure:
// <p>Paragraph 1</p>
// <p>Paragraph 2</p>
// <p>Paragraph 3</p>

const paragraphs = document.getElementsByTagName('p');

// paragraphs is an HTMLCollection
// It contains all 'p' elements in the document
// You can access them using indexes (0, 1, 2, ...)
console.log(paragraphs[0].textContent); // Output: "Paragraph 1"
console.log(paragraphs[1].textContent); // Output: "Paragraph 2"
console.log(paragraphs[2].textContent); // Output: "Paragraph 3"

getElementByTagNameNS

This is a method of the document object in JavaScript, which allows you to select HTML elements based on their namespace and local name. This method is primarily used with XML documents that have specific namespaces.

In XML documents, elements can belong to specific namespaces, The getElementByTagNameNS method allows you to select elements based on both their namespace URI and the local name. It works by searching the entire DOM for elements that match both the namespace URI and the local name. If one or more matching elements are found, getElementByTagName returns a live HTMLCollection of those elements. If no matches are found, it returns an empty collection.

Pros

Namespace Specific: Useful for working with XML documents that use namespaces to distinguish between elements.

Select Multiple Elements: Like other methods, getElementsByTagNameNs can return multiple elements.

Cons

Specific to NameSpace: This method is primarily used with XML documents and is not commonly used with standard HTML documents.

Usage

// Assume you have an XML document with a namespace:
// <ns:element>Element 1</ns:element>
// <ns:element>Element 2</ns:element>
// <ns:element>Element 3</ns:element>

const elements = document.getElementsByTagNameNS('namespaceURI', 'element');

// elements is an HTMLCollection
// It contains all elements with the local name 'element' and namespace URI 'namespaceURI'
// You can access them using indexes (0, 1, 2, ...)
console.log(elements[0].textContent); // Output: "Element 1"
console.log(elements[1].textContent); // Output: "Element 2"
console.log(elements[2].textContent); // Output: "Element 3"

querySelector

This is a method provided by the DOM(Document Object Model) API in JavaScript.It allows you to select and retrieve elements from the documents using CSS-like selectors.

To use querySelector you need to pass a CSS selector string(e.g. .myClass, #id, form, etc), The selector string identifies the elements you want to select. querySelector returns the first element that matches the CSS selector provided. If no match is found, it returns null.

Pros:

Flexible and powerful: querySelector allows for a wide range of selections, allowing you to target a wide range of elements like classes, IDs, tag names, attributes values, etc

Returns a Single Element: If you want only one element, querySelector returns the first match.

Cons

Only Returns First Match: If multiple elements match the selector, querySelector will only return the first one. You would need to use querySelectorAll , if you want to select all matching elements.

Not Supported in Older Browsers: While it is supported in modern browsers, older browsers may not fully support querySelector. Check for compatibility if you need to support older versions.

// Assume you have the following HTML structure:
// <h1 class="myClass">Element 1</h1>
// <h1 class="myClass">Element 2</h1>
// <h1 class="myClass">Element 3</h1>

const myElement = document.querySelector('.myClass');

if (myElement !== null) {
// `myElement` is the first element with the class 'myClass'
myElement.textContent = 'Hello, World!';
} else {
console.log('Element not found');
}

querySelectorAll

This is a method provided by the DOM(Document Object Model) API in JavaScript. It allows you to select and retrieve multiple elements from the document using CSS-like selectors.

To use the querySelectorAll you pass in CSS selector string(s), the selector string(s) identifies the elements you want to select. Unlike querySelector, which returns only the first matching element, querySelectorAll, returns a static NodeList containing all elements that match the CSS selector provided.

Pros

Select Multiple Elements: querySelectorAll allows you to select multiple elements that match the provided selector.

Can Use Complex Selectors: You can use complex CSS selectors, combining classes, IDs, tag names, attribute values, and more to precisely target elements.

Returns a NodeList: The result is a NodeList, which allows you to use NodeList-specific methods like forEach for iteration.

Cons

Returns a Static NodeList: Unlike HTMLCollections, which are live and updates when the DOM changes, a NodeList returned by querySelectorAll is static. It won't reflect changes made to the DOM after the query.

Usage

// Select all elements with class 'myClass'
const myElements = document.querySelectorAll('.myClass');

// Select the element with ID 'uniqueElement'
const uniqueElement = document.querySelectorAll('#uniqueElement');

// Select all elements with class 'myClass' that are also div elements
const myDivs = document.querySelectorAll('div.myClass');

// Select all elements with class 'myClass' or 'otherClass'
const multipleClasses = document.querySelectorAll('.myClass, .otherClass');

// Select the first child of an element with class 'myClass'
const firstChildOfMyClass = document.querySelectorAll('.myClass :first-child');


// Assume you have the following HTML structure:
// <h1class="myClass">Element 1</h1>
// <h1 class="myClass">Element 2</h1>
// <h1 class="myClass">Element 3</h1>

const myElements = document.querySelectorAll('.myClass');

// myElements is a NodeList containing all elements with the class 'myClass'
// You can access them using indexes (0, 1, 2, ...)
myElements.forEach(element => {
console.log(element.textContent);
});

ParentNode

This is a property of the DOM nodes in JavaScript.It allows you to access the immediate parent of a given node within the DOM tree.

The DOM represents the structure of a web page as a tree of nodes. Each node can have child nodes, and nodes are connected in a hierarchical manner.parentNode is a property of a DOM node that refers to the parent node of the current node. It is essentially the node one level above in the DOM tree. If the node has a parent, parentNode returns a reference to the parent node and it doesn’t have a parent (e.g., it’s the root of the document), parentNode returns null.

Usage

<div id="parent">
<span>Child Node</span>
</div>
const childNode = document.querySelector('span');
const parentElement = childNode.parentNode;

console.log(parentElement.id); // Output: "parent"

--

--

Ukpa Uchechi
Ukpa Uchechi

Written by Ukpa Uchechi

A Tech Enthusiastic and lover, who loves teaching and learning.

No responses yet