Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container.

For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head.

<div>
 <ul class="head">
  <li data-test="...">1</li>
  <li>2</li>
  <li>3</li>
 </ul>
 <ul class="head">
  <li>1</li>
  <li>2</li>
  <li data-test="...">3</li>
 </ul>
 <ul class="head">
  <li>1</li>
  <li data-test="...">2</li>
  <li>3</li>
 </ul>
</div>
document.querySelector('div').addEventListener('click', function(e) {

  var ul = findParentByClass(e.target, ".head");
  if(ul) { // clicked a UL }

});

function findParentByClass(node, cls) {
    while (node && !hasClass(node, cls)) {
        node = node.parentNode;
    }
    return node;
}

I want to create a new function similar to findParentByClass, but this time it would be called findParentByQuerySelector. This way, I could potentially use it like so:

li = findParentByQuerySelector('li:[data-test]');
if(li) { // clicked li with data-test attribute }

However, I am struggling to figure out how to incorporate a querySelector into this event bubbling logic.

Answer №1

If you're looking for a way to find the parent element based on a specific selector, one approach is to utilize the Element.matches method:

function getParentBySelector(node, selector) {
    while (node && !node.matches(selector)) {
        node = node.parentNode;
    }
    return node;
}

It's worth noting that the implementation of this method may not be consistent across all browsers.

Alternatively, you could opt for using Element.querySelectorAll, which searches within the specified element's children. Keep in mind that you will need to consider not only direct parents but also grandparents:

function getParentBySelector(node, selector) {
    while (node && node.parentNode) {
        let elements = node.parentNode.querySelectorAll(selector);
        if (Array.prototype.includes.call(elements, node)) {
          return node
        }
        node = node.parentNode;
    }
    return node;
}

However, it's fair to say that this method is not the most elegant solution available.

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

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

sharing data between two node.js servers using http

I am currently working on integrating two node.js/express servers that communicate with each other using HTTP. One of the servers, known as server A, is responsible for handling file upload requests from the browser. My goal is to seamlessly transfer any u ...

Steps to customize a CSS file within node_modules

Is there a way to make changes to a CSS file in the "node_modules" dependency without them being overwritten when I run npm install? I want to keep the modifications I've made to the node module files. ...

Adjusting the selected state of an HTML/CSS checkbox with JavaScript

After downloading a theme with a tailored switch component that replaces the standard checkbox functionality, I noticed that the 'checked' status of the underlying checkbox does not change upon click or touch events. Here is the HTML structure: ...

The behavior of the Ionic checkbox in version 5 seems to be quite delayed

I am facing an issue with binding the checked attribute value on an ion-checkbox, as the behavior seems to be delayed. In my .ts file, I have an array variable named user_id. In my checkbox list, I am trying to populate this array based on which checkboxe ...

Employ node's gm library in combination with promises and buffers

Using gm with Bluebird has been a bit tricky for me. Initially, I tried this approach: var gm = require('gm'); var bluebird = require('bluebird'); gm = bluebird.promisifyAll(gm); However, when attempting to execute the following code: ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

"Implementing automated default values for Select/dropdown lists in ReactJs, with the added capability to manually revert back to the default selection

After browsing multiple websites, I couldn't find a clear solution on how to both set and select a default value in a select element. Most resources only explain how to set the value, without addressing how to reselect the default value. My Requireme ...

Animate the entire paragraph with CSS hover effect

I'm seeking ideas on how to achieve a specific effect without the need to wrap individual lines in inner elements like span or a. Check out this example <div class="m-linkitem"> <h1>Hover Below</h1> <a href="#">Lorem ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

I encountered an error while trying to deploy my next.js project on Vercel - it seems that the module 'react-icons/Fa' cannot be found, along with

I'm currently in the process of deploying my Next.js TypeScript project on Vercel, but I've encountered an error. Can someone please help me with fixing this bug? Should I try running "npm run build" and then push the changes to GitHub again? Tha ...

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

validation of dialog forms

Is there a way to trigger the $("#form").validated() function from the ok button in a jquery-ui-dialog? Please note that I would prefer not to use a submit button within the form. ...

Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult. This is what I have so far, but I suspect the issue lies within the h variable. function formatTime(time) { var h = m = s = ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Guide on setting default attributes for all properties of an object at once

Currently, I'm in the process of developing an AngularJS service provider (function) that achieves the following objectives: Gathers data from multiple tables within an SQLite database Delivers the resulting object to various controller functions S ...

Storing the state of web applications in AJAX applications

How can the application state be maintained across requests for thick JavaScript clients? In addition to client managed cookies and descriptive URLs, are there any other methods? Please note that by clients I am referring to thick JavaScript clients. The ...

Obtain the count of unique key-value pairs represented in an object

I received this response from the server: https://i.stack.imgur.com/TvpTP.png My goal is to obtain the unique key along with its occurrence count in the following format: 0:{"name":"physics 1","count":2} 1:{"name":"chem 1","count":6} I have already rev ...