"Exploring Typescript return types in relation to the .getElementsByClassName() method

I am struggling to understand why there is a difference in the results when I use getElementsByClassName on two distinct elements:

Check out this code snippet:

let section:HTMLElement = document.getElementById("mainSection");

// When I run this, it returns NodeListOf<Element>
let blah1 = section.getElementsByClassName("blah");

// However, running this line gives me HTMLCollectionOf<Element>
let blah2 = document.getElementsByClassName("blah");

Why does calling the method on section give me a NodeList, while calling it on document results in an HTMLCollection?

According to the MDN Documentation, shouldn't both of them return an HTMLCollection?

Answer №1

When it comes to the javascript document object, rest assured that it only contains valid HTML elements as mandated by standards.

Nevertheless, keep in mind that HTML elements (such as your selection) have the ability to contain other HTML elements or nodes that may not be considered valid html, like plain text which is a node but cannot legally exist on its own within the JavaScript document.

Although NodeList and HTMLCollection are quite similar, from a traditional object-oriented perspective, HTMLCollection extends NodeList, meaning it has all the functionalities of NodeList while also boasting the inclusion of the namedItem method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add middleware to one individual store

When working with Redux, it is possible to create middleware that can be easily applied to the entire store. For example, I have a middleware function called socketMiddleware that connects to a socket and dispatches an action when connected. function sock ...

How to make a POST request with custom headers in NestJS

Has anyone successfully sent a Post request using Nestjs to a 3rd party API that needs authorization through a client-key and secret? I am looking for guidance on how to include headers in the request, ideally using axio's HttpService. ...

Is it possible to change the ajax src attribute without initiating a new request?

My goal is to create an iframe using a system that utilizes HTTP authentication. Below is the code I am currently working with: <iframe id="dashboard"></iframe> <script type="text/javascript"> $.ajax( ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Ignoring if/else statements in Jquery to handle click events

I am facing a frustrating issue with my JavaScript code. I had a simple task in mind – to have JS check if the child img of the clicked link has a specific src attribute and perform different actions based on the result. However, for some reason, the c ...

Using jQuery to collapse nested lists within a hierarchical structure

I'm facing a frustrating issue that seems to stem from my limited knowledge of javascript and jQuery. The problem lies within a list structured using recursion for hierarchy. Here's a snippet of the code: $(function (){ $('#foo').c ...

Ways to swap out a React component for a different one after modifying its state

I'm relatively new to React and I am currently working on a project where I need to display a large image that takes 3-4 seconds to load. To enhance user experience, I plan to implement a loader using the ReactImage component available at https://www. ...

End the SQL connection in Nodejs

I'm having trouble closing the connection for a query using connection.close(). Does anyone know how to properly close the connection inside a route file? var express = require('express'); var router = express.Router(); var connection = req ...

The gitlab CI is encountering an issue with the eslint warning

I am currently utilizing React with Typescript. I have configured eslint locally to treat unused variables as a warning. Oddly enough, when I execute npm run build on my local machine, it works perfectly fine. However, in Gitlab CI, I am encountering the ...

Developing a collection of components with customizable color variations using React

I am interested in creating a React component library where users can specify color variants. For instance, I want to use the following syntax: const customTheme = createCustomTheme({ button: { variants: { primary: 'primary ...

When populating data, two ID fields (_id and id) are generated as duplicates

Upon retrieving information from my database, I have noticed the presence of an additional id field alongside the standard _id field. These two fields consistently contain identical values. However, it seems that the id field appears only during population ...

Exploring the best practices for handling Ajax requests in React flux architecture

I have developed a react js application where users can register by creating an account, and then I send an HTTP post request to the backend server. My action function for creating a user looks like this: export function createUser(name, username, passwo ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided: "other_lessons": [ { "id": 290, "name": "Christmas Test #290", "course": { "id": ...

Only send the parameter for variables that are not empty in the AJAX data

How can I pass the variables that are not empty in the data object for an AJAX request? In this scenario, the area variable is empty so I need to pass parameters for city and listing type instead. Can someone please help me figure out how to do this? va ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Navigate to the middle of the visible area

Is there a way to automatically center a div when it is clicked, so that it scrolls to the middle of the browser viewport? I have seen examples using anchor points but I want to find a different solution. Any ideas on how to accomplish this without using ...

What is the most effective way to reset the state array of objects in React JS?

I'm facing a challenge in resetting an array of objects without having to rewrite the initial state value again. Initial state const [state, setState] = useState([ {name: 'abc', age: 24}, {name: 'xyz', age: 20} ]) Is there a metho ...

Navigating to a webpage using the href attribute in JavaScript

Due to specific design constraints, I am unable to wrap elements with an Anchor tag. However, I can implement a click event on those elements. How can I navigate to the link correctly? The code snippet from before: <a href="Page1.html"> <but ...

Issue encountered while importing dependency in Cypress Cucumber framework

Currently facing an issue with importing certain dependencies in Cucumber. The error message I received is as follows: Running: features\my_feature.feature... (1 of 1) Browserslist: caniuse-lite is outdated. P ...