Finding elements by their class name using `getElementsByClassName` method in

I am attempting to retrieve elements with the class name "special". I came across this code snippet online, but unfortunately, it only gives back an empty array.

Can anyone spot what may be going wrong?

getElementsByClassName = function (node, classname){
 var a = [],
    re = new RegExp('\b' + classname + '\b'),
    els = node.getElementsByTagName("*"),
    l = els.length,
    i;

 for (i = 0; i < l; i += 1) {
  if (re.test(els[i].className)) {
      a.push(els[i]);
  }
 }
 console.log(a)
 return a;
}

var wrap = document.getElementById('wrap');
getElementsByClassName(wrap, 'special')

The wrap element has 22 children, with the last one being

<p class="special">Lorem</p>
. In Firebug, I can locate the node with the correct class name, but for some reason, it skips the a.push. I'm at a loss here!

edit: After some further debugging, it seems that the code is working now; however, it would still be helpful to understand why console.log(a) was initially returning an empty array

Answer №1

let regex = new RegExp('\b' + className + '\b')

It is recommended to write it as:

let regex = new RegExp('\\b' + className + '\\b')

Additionally, remember to use "var " at the start of variable declarations.

Answer №2

let regExp = new RegExp('\b' + className + '\b'),

The use of \b in a string literal signifies a backspace character. The corrected expression should be:

let regExp= new RegExp('\\b' + className + '\\b');

Nevertheless, there are still issues with this implementation because:

  1. It will fail with class names that contain non-ASCII or non-alphanumeric characters due to incorrect word boundaries;

  2. Class names may include special regex characters like ., which must be escaped.

An alternative approach that aligns better with the standard document.getElementsByClassName functionality can be found in this related query.

Answer №3

It's possible I am incorrect, but it seems like the re.test(els[i].className) will not account for the \b word boundaries, causing the regex to fail.

This means that you are simply checking for the presence of "special" without any surrounding spaces, quotes, or other boundary characters.

Answer №4

To resolve this issue, you can try the following code snippet:

els = document.all ? node.all : node.getElementsByTagName("*")

I cannot recall exactly which versions of Internet Explorer do not support node.getElementsByTagName('*'), but it is certain that it will fail in certain versions. It mistakenly searches for nodes with tagNames of asterisks!

In my previous experience, I have used the following code to handle this situation:

function getElementsByTagName(node, tag) {
    tag = tag || '*';
    var els = node.getElementsByTagName(tag);
    if( !els.length && (tag == '*' && node.all) ) els = node.all;
}

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

There seems to be an issue with the integration of Bootstrap in my JavaScript file

Is there a way to ensure that each new data entry in the array appears next to each other rather than stacking beneath one another? This is a JavaScript file with HTML written in Bootstrap format. const collegeData = [{ name: "University of Penn ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

When the tabBar is hidden on a particular screen, a gray area is shown at the bottom of the page in the Expo app

I am currently working with nested routes using expo-router. When attempting to hide the tabBar for a specific page, I noticed that it still displays a gray area. To address this issue, I have set the display option to none in the tabBarStyles options and ...

What is causing the recursion function to return "NaN" in this scenario?

I'm trying to calculate the total sum of absolute differences between consecutive elements in an array using a function called sumAbsArr, but it seems to be returning NaN. var arr = [1, 5, 2]; var n = 3; var cur = 0; console.log(sumAbsArr(arr, n, ...

CSS media query to target specific viewport width

In my JavaScript code, I am dynamically creating a meta viewport. I set the value of this viewport to be 980px using the following script: var customViewPort=document.createElement('meta'); customViewPort.id="viewport"; customViewPort.name = "vie ...

"Unveiling the Benefits of Converting Body to JSON String and Object in Angular 7

Why is it necessary to convert event.body into a JSON string and then parse it back into an object? this.excelFileService.upload(this.currentFileUpload).subscribe(event => { if (event.type === HttpEventType.UploadProgress) { this.progress ...

Having trouble with loading textures in Three.js?

I'm facing an issue while trying to apply a texture to my mesh using three.js. Instead of the expected loaded texture, I am just seeing a plain black object. I followed the examples provided in the three.js documentation ( - Example) and also tried va ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Is there a way to make a <div> load automatically when the page starts loading?

I'm having an issue with my code where both <div> elements run together when I refresh the page. I want them to display separately when each radio button is clicked. <input type="radio" name="cardType" id="one" class="css-checkbox" value="db ...

Leveraging mongo-triggers for automation

I just completed the installation of mongo-triggers by running: npm install mongo-triggers Now, I'm attempting to set up a simple "hello world" example: var MongoClient = require('mongodb').MongoClient; var triggers = require("mongo-trigg ...

The middleware for express body-parser stores information in the "name" property

I'm just starting out with the nodeJS Express framework and I'm currently working on consuming a POST request that I sent using the code snippet below: router.post('/', function(req, res) { var data = Object.getOwnPropertyNames(req ...

Converting a CSV string into an array only when there is a line break in the body

Need help to convert a CSV string into an array of array of objects. Struggling with handling \n in the incoming request, causing issues with splitting and code errors. The string format includes messages enclosed in ". "id,urn,title,body,ri ...

Error: Jasmine is unable to find the module that is being referenced

When running SpecRunner.html, an error is encountered ReferenceError: module is not defined The Controller code is as follows: angular.module('mymodule', []) .controller('mycontroller', ['$scope', function($scope) ...

Retrieve the user's IP address from the request rather than Cloudflare's IP address

Cloudflare alters the IP addresses of incoming requests as it acts as a middleman between my website and the Internet, functioning as a proxy. Is there a way to retrieve the original IP address of the request, rather than Cloudflare's IP address? I h ...

What is the best way to perform a redirect in Node.js and Express.js following a user's successful login

As I work on developing an online community application with nodejs/expressjs, one persistent issue is arising when it comes to redirecting users to the correct page after they have successfully signed in. Despite reading several related articles and attem ...

Loading gltf files with Three.js does not automatically update external variables

When I import a gltf object, it seems to render in the browser but I am unable to access it using an outside variable. What could be causing this issue? let loadedModel; gltfLoader.load('./assets/javaLogo.gltf', function(gltf){ loadedModel = ...

Getting EdgesHelper to align properly with Mesh in Three.js

Within a dynamic scene, multiple mesh objects (specifically cubes) have been included. A unique EdgeHelper has been generated for each cube to track its movements and rotations. Whenever a particular cube mesh is selected, I am aiming to alter the color o ...

The Javascript toggle for hiding and showing did not function as expected

I've been attempting to create a JavaScript toggle so that when I click on any of the buttons below, only that particular div is shown and all others are hidden. Unfortunately, my code is not working as expected: function toggle(show,hide) { do ...

Fiddler is indicating that my JavaScript file cannot be found, despite the fact that it is present and functioning correctly as anticipated

In Default.aspx, I have added the following line to my javascript file: <script type="text/javascript" src="../../MyFiles/JavaScript/JavaScript.js" ></script> When testing the website using Fiddler, I repeatedly receive a 404 error indicatin ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...