JavaScript - The never-ending recursive function

At the moment, I am developing a Chrome extension that allows users to click on a node in order to access its content. While acquiring inner text using textContent is straightforward, extracting the URL of an image within a clicked div presents some challenges...

I attempted to employ this function to locate the img node and retrieve its href/src:

function getimgtag(elem) //elem represents the clicked div
{
    for(i=0; elem.getElementsByTagName('div')[i]; i++)
    {
        getimgtag(elem.getElementsByTagName('div')[i]);
    }
    if(elem.getElementsByTagName('img')[0])
    {
        localStorage['fus_imgtag'] = elem.getElementsByTagName('img')[0];
    }   

}

However, it appears to run indefinitely without completion and the reason behind this behavior eludes me. Shouldn't it iterate through all the div elements and store the last found img in localStorage['fus_imgtag']?

Answer №1

It is essential to declare variable i using var i. Failure to do so would result in it becoming an implicit global variable, causing potential issues - especially in your scenario where i needs to be scoped locally for each recursive call.

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

Utilizing fab-icons with CDN in Next.js version 13.4

Currently, I am working with the latest version of Next.js (13.4) and I would like to incorporate a single Icon into my project using Font Awesome CDN to avoid increasing the overall app size. However, when I include the following code snippet in my layou ...

MongoDB suggests

I'm currently developing an app that requires autocomplete functionality for search. I've started implementing it using regular expressions (regexp), but I'm unsure if this is the optimal approach. Each new character input in the search bar ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

ng-bind stops updating after entering text into input field

I am a newcomer to AngularJS and I have encountered an issue that I am struggling to resolve. Although I found a similar question on stackoverflow, the solution provided did not work for me. The problem I am facing is that when I input text into any of the ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

When making axios calls from React to a Node.js server, sometimes the `req.body` object

Attempting to send the two IDs (book_id, user_id) from axios to node.js results in an empty object when I console.log(req.body). When using console.log("bookid", book_id, "user", user_id) in axios, the output is: https://i.sstatic.net/d5HgQ.png Upon con ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...

Resolving Text Animation Flickering Issues in CSS and React

After successfully creating this animation using CSS animations and React, I encountered a flickering issue. The cause of this problem is unclear to me, it could be due to my usage of setInterval or potential issues with the keyframes in my CSS animations. ...

I encountered an issue while using mediaRecorder to save a JavaScript animation; the blob value returned as null

My current project involves using Vanta js to create an animated background and mediaRecorder to capture the canvas as a webm file. The recording process is supposed to start from the beginning and stop after 1 second, exporting the webm file. However, I ...

Transitioning from the older version of meteor 1.8.3 to the latest version 2.6

I'm working with an older project that is currently using version 1.8.3 of a software that supports MongoDB 5 in Meteor 2.6. I have reviewed the changelog and migration guide and now I have a question: Should I upgrade directly from 1.8.3 to 2.6, or i ...

Issue Encountered While Deploying Next JS Application Utilizing Dynamic Routing

I just finished developing my Personal Blog app with Next JS, but I keep encountering an error related to Dynamic Routing whenever I run npm run-script build. Below is the code for the Dynamic Route Page: import cateogaryPage from '../../styles/cards ...

Using JavaScript/Angular to borrow a function and add additional parameters

In my scenario, I have a service function that requires a static parameter and a second custom parameter that changes based on the controller it is being used in. I am looking for a way for my controller/view to invoke this service function without havin ...

Infrastructural setup for multiplayer games using Socket.io

var connectionHandler = function(socket) { var player = null; socket.on('login', function(data) { player = { data: okeyServer.playerJoin(data), socket: socket }; socket.emit('welcome'); }); socket. ...

Verify if an object remains within the camera's field of view using three.js

When dealing with a 2D canvas, it's common practice to determine if an element is off-screen by checking its position coordinates like so: if( pos.x > window.innerWidth || pos.x < 0 || pos.y > window.innerHeight || pos.y < 0 ) { / ...

Developing a JavaScript program for ATMs that can efficiently handle and dispense money in the fewest number of notes possible

When a certain amount is entered, the code should be capable of handling figures up to 20000. For instance, if the input amount is 2600 with a card balance of 3000, the output will be as follows: New Balance - 400 Notes: 2000 * 1 500 * 1 100 * 1 Only thre ...

Guide to updating the content of an input field

As a newcomer hobbyist, I'm attempting to automate my web browsing experience. My goal is to have the browser automatically fill in my username and password, and then click the sign-in button using a combination of JavaScript and Tampermonkey. This me ...

Slowly soften images following a brief pause

Hey there! I have a little project where I am trying to rotate images within a div every few seconds The code I currently have is functional, but there are a couple of things that I want to tweak and I'm hoping you can assist me with that: The di ...

Implementing JavaScript Functions to Trigger Control Key and Plus/Minus Events

In my project, I have a unique set of selectors called A+. By clicking on the A+ button, it has been programmed to initiate the control plus event. Similarly, within the same interface, I also have an A- button that activates the control minus event when ...

Incorrect Tooltip DisplayWhat could be causing the issue with

I am facing an issue when trying to add a tooltip to a glyphicon within a tile. It doesn't seem to work correctly when it should. However, placing the tooltip outside of the tile works fine. I'm quite perplexed and would greatly appreciate any as ...

Aligning the text vertically in the center while also rotating it 90 degrees to the right, alongside blocking the image and icon elements

I have been experimenting with Bootstrap Trying to create a layout with an image aligned to the top right, a rotated paragraph with a star symbol, and a vertical arrangement of five star symbols. Here's a screenshot of what I'm aiming for: Scre ...