Here is the code that I am trying, the DOM structure will be same.
The DOM in loaded dynamically, that why I am trying with document click. We need to get the colour of the current clicked box. With jQuery its easy, unable find solution in javaScript. Can anyone help to resolve this?
document.addEventListener("click", function(e){
const CTABtn = e.target.closest(".btn");
if(CTABtn){
alert('the color of the box');
}
});
.container{
display:flex;
flex-wrap:wrap;
justify-content:space-evenly;
}
.box{
border:1px solid black;
padding:5px;
}
<div class="container">
<div class="box">
<div>
<h1>Red</h1>
</div>
<div>
<button class="btn">CTA</button>
</div>
</div>
<div class="box">
<div>
<h1>Green</h1>
</div>
<div>
<button class="btn">CTA</button>
</div>
</div>
<div class="box">
<div>
<h1>Blue</h1>
</div>
<div>
<button class="btn">Blue</button>
</div>
</div>
</div>
3
Answers
You’re on the right track with
closest
, but what you want to do is find the closest containing.box
(rather than.btn
) and then, from there, find theh1
element in the box to get the text from it:It would be a lot easier if you just added the color as a data attribute on the button.
There are multiple ways to do what you want to do, you can access the parent and get the child or reference a sibling
There is another, but a bit more complicated way of doing that: