Is it necessary to convert an HTMLCollection or a Nodelist into an Array in order to create an array of nodes?

Here we go again with the beginner guy. I'm working on this exercise from a book called "Eloquent JavaScript". The goal is to create a function similar to "getElementByTagName". However, the first function below is not returning anything and the second one is struggling to pass through the "if" statement after the "while" loop.

Cheers,

function findTags(node, tagName) {

    let tagArray = [];
    let childrenNode = node.childNodes;

    if(childrenNode.length != 0) {
        for(let i = 0; i < childrenNode.length; i++) {
            let currentNode = childrenNode[i];
            if(currentNode == Node.ELEMENT_NODE && currentNode.nodeName == tagName.toUpperCase()) {
                tagArray.push(currentNode);
            }
            let child = findTags(currentNode, tagName )
            if(child) {
                tagArray.concat(child);
            }
        }    
    }
    return tagArray;
}

function findTags(node, tagName) {

    let tagArray = [];
    let currentNode = node.firstElementChild;

    while(currentNode != null) {
        if(currentNode.tagName == tagName.toUpperCase()) {
            tagArray.push(currentNode);
        }
        let descendant = findTags(currentNode, tagName );
        if(descendant) {
            tagArray.concat(descendant);
        }
        let currentNode = currentNode.nextElementSibling;
    }    
    return tagArray;
}

Answer №1

You overlooked a crucial detail in your logic. Instead of comparing the node with the expected node type, you need to check the type of the node itself:

currentNode.nodeType == Node.ELEMENT_NODE

In addition, the following code snippet doesn't serve any purpose:

tagArrays.concat(child);

The concat() function creates a new array instead of modifying the existing one. To add items to tagArrays, you should consider using one of the following approaches:

tagArrays = tagArrays.concat(child);

or 

tagArrays.push(...child);

or

tagArrays.splice(tagArrays.length - 1, 0, child);

Answer №2

Currently, you are comparing the currentNode (a Node) to Node.ELEMENT_NODE (a number), resulting in it always evaluating to false. To correct this, ensure to include the nodeType property when referencing the currentNode within the initial if statement inside the for loop:

function tagSearch (node, name) {

    let tagArray = [];
    let childNodes = node.childNodes;

    if(childNodes.length != 0) {
        for(let i = 0; i < childNodes.length; i++) {
            let currentNode = childNodes[i];
            if(currentNode.nodeType == Node.ELEMENT_NODE && currentNode.nodeName == name.toUpperCase()) {
                tagArray.push(currentNode);
            }
            let child = tagSearch(currentNode, name )
            if(child) {
                tagArray.concat(child);
            }
        }    
    }
    return tagArray;
}

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

When developing a website in Sitecore 8, the link consistently opens in a new window rather than a new tab, even after including the target="_blank" attribute

When using Sitecore-8 CMS, external links are set to open in a new window instead of a new tab in Internet Explorer 10 and IE 9, even when target="_blank" is included in the href tag. We are seeking a solution to address this issue. Any assistance would b ...

How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps. I have obtained this SVG file: <svg xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510"> <g stroke="black" stroke-width="10" ...

Can you transform your content like Google does?

Looking to create a help page with a layout similar to http://support.google.com/plus/?hl=en. Can anyone provide advice or an example of how to update the new content list without refreshing the page? When you click on something like "circles and streams" ...

Pulling JavaScript - referencing an external script

I am currently facing a challenging dilemma that requires a simple yet intricate solution. My objective is to develop a script capable of playing chess on my behalf, utilizing an engine to determine the optimal moves for pieces such as rooks, bishops, king ...

What is the best approach to integrating an idle timeout feature with identityserver4 and aspnet identity for a secure implementation?

Currently, I am developing a login site using IdentityServer4 (server UI) with .NET Identity in .NET Core 2.2 Razor Pages. I have implemented a javascript modal alert that notifies users of an impending idle timeout and redirects them to the logout screen ...

Ensuring Form Accuracy - Mandatory Selection from Group

Currently, in the project I am working on, there are three textboxes that need to be validated to ensure at least one of them has been filled out. I have been researching custom validation with Angular directives and found that it is possible to set the v ...

Having trouble with custom padding for b-sidebar in VueJS?

I am struggling with adding padding to the sidebar using bootstrap-vue. When I attempt to add padding in the browser devtools, it works perfectly fine. However, when trying to implement the same code, it doesn't reflect on the actual webpage. I tried ...

Does the body element inherit the line height property?

Below is some simple HTML code consisting of a div and a span: <div id="container">Some text to affect the width</div> <span>A</span> I am currently using Eric Meyer's CSS Reset, which sets the line-height of the body to 1 an ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Utilizing various camera set-ups within Three.js

How can I smoothly switch between two different cameras in Three.js while transitioning from one to the other? Imagine a scene with a rock and a tree, each having its own dedicated camera setup. I'm looking for a way to seamlessly transition between ...

Tips for configuring formik values

index.js const [formData, setFormData] = useState({ product_name: 'Apple', categoryId: '12345', description: 'Fresh and juicy apple', link: 'www.apple.com' }); const loadFormValues = async () => { ...

The SVG animation is reversing and decreasing in size from the bottom

Feeling lost, I spent a day searching without success. I have a project in full Vuejs and I thought using Svg would be easy and fun, but I can't figure out why the image resizes when playing an animation. The bottom of the svg seems to resize and get ...

Creating a standalone card using Bootstrap

Trying to create this... https://i.stack.imgur.com/PMRSI.png However, I'm unsure of how to achieve it. <div class="row justify-content-center"> <div class="col-3 me-3" style="background-color: #F1F3F8; border-r ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

Site optimized for mobile devices

I need to create a website that is optimized for mobile devices like Android, iPhone, and Blackberry, as well as desktop and tablet. The screen resolutions of these devices can vary greatly. My supervisor has suggested developing one site that can adjust ...

What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects: The first one is a role object with the following properties: Role { roleId: string; name: string; description: string; isModerator: string; } role = { roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1", ...

Is there a way to convert the existing JavaScript code for a hyperlink so that it can be triggered by clicking a button instead?

I have a JavaScript code that works well when the hyperlink below is clicked: <a href="delete_event.php?event_id=110" onClick="return ConfirmDelete()" class="list-group-item">Delete Event</a> <script> function ConfirmDelete() { var ans ...

such as in the post schema, the word "like" does not

like not removing from post model likeSchema .findOne({$and: [{post: postId ,user: userId}]}) .exec((err, result) =>{ if (result) { db.likeSchema .findOne( { $and ...

The data retrieved from the backend is being stored in an object, however, it is not directly accessible through

After receiving data from the backend and storing it in an object, I am facing an issue where trying to print it using object properties shows undefined values. Here is a snapshot of my output: view image here Snippet of my code: this.documentService.getD ...

Design a customizable overlay with a moveable and size-adjustable layer below it

After working with kineticjs, I successfully created an app that allows images to be draggable and resizable, which is great progress; Now, I am facing a challenge: I want to have an overlay in the center with a block of variable height/width that display ...