Reputation: 65
I tried to add a class to the text container that I click on and then the class assigns a color to the text I click on. the problem is when i click the same text twice, the class won't be removed. Any solution for this case?
PLEASE DON'T CHANGE WHERE THE CLASS IS
const contain = document.querySelector('.contain');
const inConts = document.querySelectorAll('.in-cont');
contain.addEventListener('click', e => {
for (inCont of inConts) {
inCont.classList.remove('red');
}
if (e.target.classList.contains('txt')) {
e.target.parentElement.classList.toggle('red');
}
});
.in-cont.red .txt {
color: red;
}
<div class="contain">
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
</div>
Upvotes: 2
Views: 45
Reputation: 25406
You can easily toggle the class red
using closest
as:
closest
searches the DOM upwards for an element that matches the selector. This search includes the element itself.
element.closest(selector)
If it finds an element that matches the selector, it returns the element. If it doesn’t find any elements, it returns
null
const contain = document.querySelector('.contain');
const inConts = document.querySelectorAll('.in-cont');
contain.addEventListener('click', e => {
if (e.target.closest("div.contain")) {
e.target.closest("div.in-cont").classList.toggle("red")
}
});
.in-cont.red .txt {
color: red;
}
<div class="contain">
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
</div>
Upvotes: 2
Reputation: 31992
When removing the red
class, check whether inCont
contains the event target:
const contain = document.querySelector('.contain');
const inConts = document.querySelectorAll('.in-cont');
contain.addEventListener('click', e => {
for (inCont of inConts) {
if (!inCont.contains(e.target)) {
inCont.classList.remove('red');
}
}
if (e.target.classList.contains('txt')) {
e.target.parentElement.classList.toggle('red');
}
});
.in-cont.red .txt {
color: red;
}
<div class="contain">
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
<div class="in-cont">
<p class="txt">Lorem ipsum dolor sit.</p>
</div>
</div>
Upvotes: 1