Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from the dropdown menu, it also triggers the parent "day" element, creating another dropdown menu with different times upon initial selection. How can I implement a JavaScript if statement that specifically detects clicks on child elements and not parent elements?

JavaScript:

function create_dropdown(day){
        var insertdiv = document.createElement('select');
        insertdiv.className = "times";;
        day.appendChild(insertdiv);
        for(var i=0;i<times_full.length;i++) {
            insertdiv.options[insertdiv.options.length] = new Option(times_full[i], i);
        }
    }

document.querySelectorAll(".day").forEach(day => {
    day.addEventListener("click", event => {
        event.currentTarget.classList.toggle("selected");
        if(event.currentTarget.classList.contains('selected'))
        {
            day.style.backgroundColor='#B0E0E6';
            create_dropdown(day);
        }
        else
        {
            day.style.backgroundColor='transparent';
        }
    });
});


var times_full = [
  "12:00 AM",
  "1:00 AM",
  "2:00 AM",
  "3:00 AM",
  "4:00 AM",
  "5:00 AM",
  "6:00 AM",
  "7:00 AM",
  "8:00 AM",
  "9:00 AM",
  "10:00 AM",
  "11:00 AM",
  "12:00 PM",
  "1:00 PM",
  "2:00 PM",
  "3:00 PM",
  "4:00 PM",
  "5:00 PM",
  "6:00 PM",
  "7:00 PM",
  "8:00 PM",
  "9:00 PM",
  "10:00 PM",
  "11:00 PM"
];

An illustration of these elements can be seen here:

https://i.stack.imgur.com/ka1gK.jpg

Answer №1

Make a small tweak to your existing code by inserting

if( even.target.parentElement.matches('.day') ) { }
inside the event listener function.

(Remember, event.target represents the actual element clicked, while currentTarget refers to the element with the listener attached).

document.querySelectorAll(".day").forEach( day => {
    day.addEventListener("click", event => {
        if( event.target.parentElement.matches('.day') ) {
            event.currentTarget.classList.toggle("selected");
            // Additional functionality can go here
        }
        

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

A guide on showcasing real-time data with Angular's service feature

home.component.ts <h1>{{ (reportsToday$ | async)}}</h1> <div echarts [options]="alertsDaily$ | async"> <div echarts [options]="alertsToday$ | async"> <div [onDisplay]="alertsDaily$ | async"> report.component.ts constructor( ...

Learn how to upload an image using Vue.js and then trigger a custom method

Greetings! I am a newcomer to Vue.js and I have encountered a problem that I need help with. In my component, there is a hidden input for files. When I click a button, the browser displays a window for importing files from my PC. Once I choose a file, I wa ...

problems arise due to padding and floating on the navigation bar

I have been facing a couple of challenges with my code. Firstly, I am trying to remove the small annoying line underneath my selected navigation links and also attempting to float both the header and footer to the right without losing their backgrounds. I ...

Rails: Generating HTML output straight from the controller

Looking for some guidance on handling the response from an AJAX call. Here's what I'm trying to achieve: Initiate an AJAX call to my Rails application to retrieve an HTML document. In the Rails controller, access the HTML document stored on dis ...

Expanding the row beyond the container to match the width of the viewport

Can Bootstrap 5 be used to extend a row outside a container without causing a horizontal scrollbar? After researching the questions related to this topic, it seems that pseudo-elements are commonly used. However, when attempting to use a pseudo-element, a ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...

Having trouble creating a full-screen modal with NgbModal by passing content as a component?

I've been using Bootstrap widgets and trying to create a full-screen modal where the header sticks on top, the footer stays at the bottom, and the body scrolls in the middle. Initially, I found a simple HTML solution for this: However, when I want to ...

Troubleshooting $scope.$on unit testing - event not getting detected

In one of my controllers, I have implemented a simple $scope.$on function: app.controller('MyController', function($scope) { $scope.$on("myBroadRcvr", function(event, data) { $scope.name = data.name; $scope.empID = data.empID ...

Struggling to save the resolved data from a promise in Node.js to a variable

I am currently utilizing nodejs to develop REST APIs and I am facing an issue with storing resolved data from multiple promises into a single variable. Here is a snippet of the code I am working with: var resultset={}; function getAllTeams() { retu ...

Creating a custom button in PHP

Currently, I am in the process of developing a shopping cart feature. One key requirement is to send both the product ID and the desired quantity chosen by the user to another file named cart.php. Below is an excerpt from my code snippet: for($i=0;$i< ...

What is the best way to display a welcoming message only once upon visiting the home page?

After gaining experience working with rails applications for a few months, I have been tasked with adding a feature that displays a welcome message to users visiting the site home page for the first time, but not on subsequent visits or page reloads. What ...

Can we implement attribute selectors in Material-UI while utilizing makeStyles?

Is it possible to extract all the div elements with specific Mui class names such as access-MuiPickersCalendarHeader-switchHeader, access-MuiPickersDay-day? My components are styled using StylesProvider which adds "access" as a prefix to the original Mater ...

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

Choose a specific example using the class name in nicEdit

Is there a way to select an instance using nicEdit based on its class name rather than just its id? For example: <div class="myInstance1"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed magna dolor, faucibus ac, iaculis non, cursus et ...

Issue with initializing MdTable in Vue Material when fetching data

After encountering a null error while trying to fetch remote data to initialize the MdTable component, I shared my issue here. The data is retrieved from a MySQL database as part of a Laravel 5.6 API project. Upon thorough investigation, it seems that the ...

My webpage lacks responsiveness

I've recently put together an HTML page, but unfortunately, it's not responsive. My Code <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> ...

What are some ways I can showcase the outcomes of my multiple choice quiz?

I need help with my multiple choice quiz. I want to display the answers under each question and highlight the correct one in bold. Here is the current code: function check() { var question1 = document.quiz.question1.value; var question2 = document.q ...

using javascript to target a specific css selector attribute

I have a CSS file with the following code: .datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4; font-size: 16px ;font-weight: normal; } Is there a way to use JavaScript to dynamically change the font size? The code below worked ...

Navigate to a particular row in jsgrid

I've implemented JS Grid for rendering data in a grid view from . The grid I'm using has multiple pages. I need to navigate to the page that includes the newly inserted row and highlight it after insertion. Is there an option in jsgrid that allo ...

Can regular JavaScript objects contain jQuery objects?

Lately, I've been working on optimizing the code for a carousel I built. One idea I'm toying with is organizing all my variables and functions into a JavaScript object to keep them separate from the rest of the code in the file (which happens to ...