What is the best way to apply a CSS class to a div element without affecting its child elements using JavaScript?

Currently, I am using JavaScript to add and remove a CSS class through a click event. Within my div structure, I have multiple similar divs. While I can successfully add and remove the class from my main div, I am facing an issue where the class is also applied to child elements like headings and paragraphs.

let heading = document.querySelectorAll(".sf_day_card_heading");

heading.forEach((el) => {
  el.addEventListener('click', (event) => {
    heading.forEach((e) => e.classList.remove('bg_yellow'));
    event.target.classList.add('bg_yellow');
  })
})
.bg_yellow {
  background: yellow;
}
<div class="sf_day_card_heading">
  <h5>MON</h5>
  <p>January 9</p>
</div>

<div class="sf_day_card_heading">
  <h5>MON</h5>
  <p>January 9</p>
</div>

Answer №1

Prefer using currentTarget over target

event.currentTarget.classList.add('highlight');

target is the specific element that initiated the event
currentTarget is the element where the event listener is attached

Answer №2

const headers = document.querySelectorAll(".sf_day_card_heading");

headers.forEach((element) => {
  element.addEventListener('click', (event) => {
    element.classList.toggle('bg_yellow');
  })
})
.bg_yellow {
  background-color: yellow;
}
<div class="sf_day_card_heading">
  <h5>MON</h5>
  <p>January 9</p>
</div>

<div class="sf_day_card_heading">
  <h5>MON</h5>
  <p>January 9</p>
</div>

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

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

What is the best way to get rid of trailing numbers in material UI class names?

The standard class for the material ui input box is .MuiInputBase-input, but when I inspect it using developer tools, I see that the same class is displayed as .MuiInputBase-input-619. How can I remove the suffix from the class name? I am currently utili ...

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...

You have attempted to make an invalid hook call in the react chat app. Hooks can only be called within the body of a function component

Encountering problems like manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. **Important Error Message/User Notification:** react-dom.development.js:20085 The above error occurred in the <WithStyles(ForwardRef(AppBar))> component: Arrange ...

I Am unable to locate the '...' after applying the text-ellipsis style to a div

https://i.stack.imgur.com/Tsmf5.png The ellipsis '...' is not showing up even after I have applied text-ellipsis, overflow hidden, and nowrap to this div. Take a look at my code: import Image from "next/future/image"; import Link from ...

What is the best way to change the state of an Object?

I need to dynamically adjust the internalstatus based on the values of externalValues. If valueOne is true, then I want statusOne to be true. Similarly, if valueTwo is true, I want statusTwo to be true and statusOne to be false. const externalValues = { v ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

Transferring information from socket.io to vue.js

I am currently facing an issue with passing socket.io data to a Vue.js element. Despite going through the Vue documentation multiple times, I have not been able to find a solution. The data is being sent to the client via socket.io and successfully logged ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

What is the best way to configure dependencies for a production deployment when utilizing Babel within the build script?

From what I understand, Babel is typically used for compiling code, which is why it usually resides in devDependencies. However, if I incorporate the Babel command into my build script and want to run npm install --only=prod before running npm run build d ...

Exploring the world of React and Material Ui

As I delve into working with Material Ui in React, I am encountering difficulties when trying to customize the components. For instance, let's take a look at an example of the AppBar: import React from 'react'; import AppBar from 'mat ...

Ways to automatically display the date upon loading the view

I have integrated a plugin with Angular, which is essentially an extension. Upon loading the view, only an empty input is visible. Clicking on the input reveals a calendar with today's date displayed. My objective is to automatically load today&apos ...

Optimal approach for handling large JSON files

I am in possession of a JSON file containing approximately 500 lines. I am hesitant to simply dump this JSON data into the end of my Node.JS file as it doesn't seem like the most efficient approach. What alternatives or best practices can be recommend ...

What could be the reason for the CSS file not getting applied to the HTML in my project?

Having trouble applying an external CSS file to my HTML file. Currently working on a Cloud IDE (goormIDE, similar to C9) and trying to link an external CSS file to my HTML file on the web server using Node.js. However, the CSS file is not being applied to ...

Unable to render a child div completely opaque using the opacity attribute

I am currently working on a popup feature that, when displayed, will blur the background of the page to a grey color. The .cover element is responsible for this overlay effect. Unfortunately, I am facing issues overriding its default opacity:0.6; property ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

Instructions on inserting an IFRAME using JavaScript into dynamically loaded content via AJAX

How can I dynamically add an IFRAME using JavaScript to content that is refreshed via AJAX? Consider the following example: $('#bar').delegate('.scroll-content-item span a', 'click', function() { var object_id = $(this).p ...

What is the best approach to increase the height of a div element dynamically

I've encountered an issue with a div tag containing an image that may exceed the screen size. When this happens, I want to increase the height of the div tag and have a footer displayed below it. Currently, my styling for the div tag looks like this: ...

Is it common for functions to be outlined in standard CSS practices?

I am curious if the CSS standard includes definitions for "functions"; I have not come across any information about them on w3schools or other sources. When I refer to "functions," I am talking about calls such as rgb(int, int, int) or url(string) that ar ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...