Finding the parent elements of an element without using jQuery's .parents() method or querySelector

Similar Question:
Check if event target parent element matches selector in JavaScript

I have a DOM element that I want to compare with all its parent elements against a specific selector, similar to the functionality of jQuery's .parents('selector') method. However, I do not require backwards compatibility and prefer not to use any libraries. I am specifically looking for a method that returns a boolean value.

I can create a recursive function, loop, or while statement using matchesSelector() myself, but I am interested in discovering lesser-known methods or more efficient code. The goal is to save process time, especially when dealing with tens of thousands of matching checks or even more.

Answer №1

When dealing with an unknown number of parents, it is recommended to utilize a while() loop.

Check out the demo on jsFiddle

function findParentElements(element, parentSelector /* optional */) {

    // If no parentSelector is specified, the function will bubble up all the way to *document*
    if (parentSelector === undefined) {
        parentSelector = document;
    }

    var parentElements = [];
    var currentElement = element.parentNode;
    
    while (currentElement !== parentSelector) {
        var tempElement = currentElement;
        parentElements.push(tempElement);
        currentElement = tempElement.parentNode;
    }
    parentElements.push(parentSelector); // Add the specified parentSelector at the end
    
    return parentElements;
}

Description: Retrieves an array of "parent" elements

// Providing only one argument will bubble up to the document
findParentElements( document.getElementById('me') ); 

// Get all parent elements starting from -me- up to the element with ID -outerParent-
findParentElements( document.getElementById('me'), document.getElementById('outerParent') );

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

Using AngularJS to handle promises within a recursive function

I have been attempting to implement the AngularJS promise/then functionality with a recursive function, but I am facing an issue where the then-function is not being called. None of the error-, success-, or notify-callbacks are getting triggered. Below is ...

Having trouble replicating the progressive response from the server in node.js

Hey there, I recently dipped my toes into the world of node.js and decided to give it a shot. Following Ryan Dahl's tutorial (http://www.youtube.com/watch?v=jo_B4LTHi3I) as my starting point, I reached a section around 0:17:00 where he explains how s ...

I'm experiencing an issue where my drum app element does not refresh after performing an action dispatch

Struggling with my React/Redux drum app, I'm at a roadblock with the final component that should update with the selected object's ID through an action dispatch. It baffles me why the element won't reflect the changes even though I've c ...

Issue with VueJS computed property failing to update when using a boolean prop

I'm facing an issue with a Vue (2.6.11 via Nuxt) component that receives a Boolean property from its parent and uses it to calculate additional computed properties. Everything displays correctly after the initial rendering. However, when the parent to ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...

Combining the `vuex-typex` npm package's `dist/index.js` for optimal performance with Jest testing framework

I initially raised this question as an open issue on GitHub. My experience with Vue.js, Vuex, TypeScript, and vuex-typex has led me to encounter syntax errors during Jest testing. I am relatively new to working with Vue.js, TypeScript, and Jest. It is wo ...

What are the benefits of using a static method in JavaScript?

I am trying to develop a method in JavaScript that can validate data in a similar way to C# syntax. Here is an example of my C# code: public static class Validate { public static bool IsValid(this string modelState) { return !String.Is ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

I would like to learn how to retrieve the value of a dynamically created control in the code behind that was initially generated by JavaScript

How do I retrieve the value of a dynamically created control in CodeBehind using JavaScript? I have generated the controls dynamically with the code snippet below: let counter = 0; let words; let foo;//span tag function add(i) { let counter = 0; ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Additional unnecessary event listeners (deleteComponent) were provided to the component but could not be inherited automatically

Dear community, I am facing an issue with emitting events from my child component to the parent. Strangely, all other components work perfectly fine with the same code except for this particular one. Let me provide you with the relevant code snippets: Ch ...

Enhance User Experience with React JS Multi-Select Dropdown Feature

I am dealing with 4 select dropdowns. The values selected should not be available in the remaining dropdown lists. Here is an overview of my state: this.state = { selectedDropdownArray: {}, dropdownArray: ['select', '1', &apos ...

Is it possible for me to choose classes in a specific sequence like this?

Is it possible to select individual DIVs generated by Wordpress using JS? Can they be selected based on the order in which JS finds them in the HTML? I attempted to add an index number to achieve this, but it seems that is only used for the LI element. Ho ...

Unauthorized changes made without verification

I'm in the process of developing a website that allows users to post without needing to create an account. Upon posting, users will be prompted to enter their email address. After posting, users will receive an email with a unique URL that grants th ...

Incorporating string input values into a function

I am currently working on a function that retrieves the value of an input upon clicking a button. My goal is to then have another event that will incorporate that value into a function when the button is clicked. var getInput = function() { $('#inpu ...

Acquiring the console log data from Firefox version 43 using Selenium, all without the use of any

Can Selenium retrieve the console.log from browsers like Firefox 43? If so, how can it be done? My settings are as follows: DesiredCapabilities capabilities = DesiredCapabilities.firefox(); LoggingPreferences logs = new LoggingPreferences(); logs.enable( ...

Preventing automatic interpretation of double curly braces within a Script tag in Handlebars

In my development project, I am constructing a visual representation of a database table along with various web application functionalities. The technologies being utilized include node.js, express, mysql, bootstrap, and handlebars. Within my pages.js fil ...

Using the i18next Module for Localization in ExpressJS and Front-End Development

I am currently integrating the i18next module into my NodeJs/ExpressJS web application. All the translation files are stored in the /locales directory. According to information from i18next.com, it can also be utilized on the client side. <script typ ...

I'm encountering a mysterious error with an undefined string. Can anyone provide guidance on how to resolve this issue

I need help making adjustments to my code in order for people on Discord to write into my text file without creating an extra blank line. Currently, my code looks like this: client.on("message", msg => { const triggerWords = ['ff']; const ...