Murakami
Murakami

Reputation: 3760

Cannot remove class in div from within, JS

As you can see I would like to remove extended class from a parent div. For some reason that does not work. How can I make it to work?

function closeExpandedProject() {
  const expandedElement = document.querySelector('.expanded');
  expandedElement.classList.remove('expanded');
}
.expanded { border: 1px solid black; }
<div class="project-item-wrapper expanded">
  Here is some text
  <span class="close" onclick="closeExpandedProject()">X</span>
</div>

Upvotes: 1

Views: 75

Answers (3)

Murakami
Murakami

Reputation: 3760

So yes, it works, but the problem comes from a different source. I had also second listener which were adding this class. So after using stopImmediatePropagation everything works just fine. Sorry for confusion if any.

Upvotes: 0

Nabeel Mehmood
Nabeel Mehmood

Reputation: 398

Use a target selector to add the event listener to the object instead of writing onclick=foo()

You can do it using Id or the ClassName.

With ClassName, it selected a list of objects so you have to access the 0th index

document.getElementsByClassName("close")[0].addEventListener("click", closeExpandedProject);

Works directly with Id

document.getElementById("close").addEventListener("click", closeExpandedProject);

function closeExpandedProject() {
  console.log("in function")
  const expandedElement = document.querySelector('.expanded');
  expandedElement.classList.remove('expanded');
}

document.getElementsByClassName("close")[0].addEventListener("click", closeExpandedProject);
.expanded { border: 1px solid black; }
<div class="project-item-wrapper expanded">
  Here is some text
  <span class="close" id="close">X</span>
</div>

Upvotes: 0

Hannan Ayub
Hannan Ayub

Reputation: 408

I believe The problem is you are selecting through querySelector is not the parent of the element you clicked. You have to select the parentNode of the clicked element.

This may solve your problem:

<div class="project-item-wrapper expanded">
  <span class="close" onclick="closeExpandedProject(this)">X</span>
</div>

Javascript:

function closeExpandedProject(element) {
    const expandedElement = element.parentNode;
    expandedElement.classList.remove('expanded');
  }

Upvotes: 2

Related Questions