Is there something I'm overlooking, or is this behavior unusual for an "if statement"?

I am facing an issue with returning a value from a function. It seems like a simple task - just looping through my HTMLElements and returning the one I need.

This problem is new to me, and I have spent a considerable amount of time debugging the code and trying different approaches to make it work or understand why it's not working as expected.

Any help and insight would be greatly appreciated.

Below is the snippet of the function that I am calling from an event listener triggered by RXjs - fromEvent

I believe the code is fairly self-explanatory, but if you require more details, I can provide my entire code.

function findElementByDataValue(target: EventTarget, data: {key: string, value: string}){
  // attempting to return from a function
  function send(element) {
    return element;
  }

  if(target && target.dataset){

    if(target.dataset[data.key] === data.value) {
      // console.log(target);
      // send(target);
      return target;
    } else {
      if(target.children){
        for (const child in Object.entries(target.children)) {
          const element = target.children[child];

          findElementByDataValue(element, data);
        }
      }
    }
  }
}

You can view the complete code on StackBlitz

*Function called at line:* 65 *Function definition at line:* 34

Answer №1

Execute the findElementByDataValue function and return the result if a matching element is found. If not, the recursive call will not perform any action in the else block:

function findElementByDataValue(target: EventTarget, data: {key: string, value: string}){
  // Function to return an element
  function send(element) {
    return element;
  }

  if(target && target.dataset){

    if(target.dataset[data.key] === data.value) {
      // console.log(target);
      // send(target);
      return target;
    } else {
      if(target.children){
        for (const child in Object.entries(target.children)) {
          const element = target.children[child];

          const result = findElementByDataValue(element, data);
          if (result) {
            return result;
          }
        }
      }
    }
  }
}

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

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Implementing CSS styling within a JavaScript file

I have a vague memory of an easy way to incorporate CSS code within a JS file, but I can't recall the specific details. Simply inserting CSS code into a JS file doesn't seem to work, so there may be a need for comments or some other method. *No ...

Even after rigorous type checking, TypeScript continues to throw the ts2571 error when handling an unidentified variable

Consider this scenario: the code snippet below will result in an Object is of type 'unknown'. error: let obj: {[key: string]: unknown} = {hello: ["world", "!"]}; // Could be anything with the same structure let key = "he ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

Angular ng-repeat not recognizing nested ng-if conditions

Hey there, I'm trying to make sure that only the option corresponding to the code used by the client to log in is displayed. The HTML should show the option that matches the client's login code. View: <div class=""> <select id="custo ...

Retrieving data from a server using the GET method with parameters through axios in a React Native application

As someone new to Web requests, I have encountered a challenge that seems simple but has proven difficult for me. Despite searching the web, I am struggling to get a working response. When I input the URL 'http://www.test.com/callservice.php?action=s ...

Passing a string to a function in AngularJS through ng-click

How can I pass a string to a function using ng click? Here's an example: HTML <a class="btn"> ng-click="test(STRING_TO_PASS)"</a> Controller $scope.test = function(stringOne, stringTwo){ valueOne = test(STRING_TO_PASS); } Edit - ...

Bootstrap icon issue: square displaying instead of the intended icon

I am currently in the process of creating a responsive website using Bootstrap 3. I have successfully downloaded and imported Bootstrap 3 into the root directory of my website. However, I have encountered an issue where the icon does not display correctly ...

Effortlessly glide through entire pages using the mouse wheel for seamless scrolling

I provide a seamless full-page scrolling experience using the mouse wheel. However, the scrollIntoView function does not seem to function within the @HostListener('wheel', ['$event']). Here is a snippet from app.component.html file: & ...

What is the reason behind eslint not permitting the rule option @typescript-eslint/consistent-type-imports?

Upon implementing the eslint rule, I configured it like this. module.exports = { rules: { "@typescript-eslint/consistent-type-imports": [ "error", { fixStyle: "inline-type-imports" ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

How can I retrieve the class of the parent element by referencing the child id in jQuery?

I want to trigger an alert on click from the child id <th id="first"> to the table(parent) class. alert($(this).parent('tr').attr('class')); This code helped me to get the class of the <tr>. However, when I try to get the ...

Encountering failures while running Angular tests in GitHub Actions due to reading inner text (which works fine locally)

I am facing an issue in my GitHub actions workflow where Karma is unable to read the 'innerText' of a native element for an Angular project. The error 'TypeError: Cannot read properties of null (reading 'innerText')' is being ...

How can you use JavaScript and regex to extract the word before a comma?

Hey there, I'm attempting to extract the word right before a comma in a sentence. For instance, consider the following string: "Cloudy, and 51 ° F " I aim to retrieve CLOUDY as the output. Could someone guide me on how to achieve this using regex ...

Despite seeming false, my Javascript if statement still evaluates to true

On my webpage, I have a button and a form. The intended functionality is for the button to display the form when clicked, and hide it when clicked again. The issue I'm facing is that no matter if the statement is true or false, the first if statement ...

How can I dynamically load a 3D model (in JSON format) at the current location of the mouse using Three.JS?

I'm currently working on a feature that involves loading a 3D model based on the mouse's position. Utilizing jQuery drag and drop functionality for this purpose has helped me load the model onto the canvas successfully, but I'm facing issues ...

Expand the initial expansion panel within an Angular Material accordion by opening the first attachment

In Angular Material expansion panels, the expanded input can be used to automatically open a specific panel when the page loads. However, in my dynamic accordion where all panels are optional, I want the first panel to be opened by default. I could manual ...

Changing Image Size in Real Time

Trying to figure out the best way to handle this situation - I need to call a static image from an API server that requires height and width parameters for generating the image size. My website is CSS dynamic, adapting to different screen sizes including ...

What is the reason behind having to coerce the enum value before the object type can be properly recognized?

My object is discriminated based on the type property, which can be any value from a specified enum. I encounter an issue in TypeScript when passing a valid object to a function; it complains about mismatched types. However, coercing the enum value resolve ...

Tips for incorporating the camera from fbxloader into your three.js scene

I am currently utilizing fbxloader from three.js to incorporate a model into my scene. I have noticed that the most recent version of fbxloader.js (https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/FBXLoader.js) has the capability to read ...