Home > Blockchain >  How to add a CSS class to a div but not to its children with JavaScript?
How to add a CSS class to a div but not to its children with JavaScript?

Time:01-26

I am adding and removing a CSS class with JavaScript through a on click event. This is the structure of my div i am using. I have a few more divs like the one here. I am able to remove and add the class to my div, but I want to be able to add it only to the div and not to the child elements like the heading and paragraph.

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 >
  <h5>MON</h5>
  <p>January 9</p>
</div>

<div >
  <h5>MON</h5>
  <p>January 9</p>
</div>

CodePudding user response:

Use currentTarget instead of target

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

target element that triggered the event
currentTarget element that has the event listener

CodePudding user response:

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

heading.forEach((el) => {
  el.addEventListener('click', (event) => {
    el.classList.toggle('bg_yellow');
  })
})
.bg_yellow {
  background: yellow;
}
<div >
  <h5>MON</h5>
  <p>January 9</p>
</div>

<div >
  <h5>MON</h5>
  <p>January 9</p>
</div>

  • Related