I'm trying to display a text in the closest element with the .msg class, but it always displayed in the first element with .msg class.
let btn = document.querySelectorAll('button');
btn.forEach(function(i) {
i.addEventListener('click', function() {
let x = document.querySelector('.msg').innerHTML = i.innerHTML;
let z = x.closest(".msg");
});
});
<div>
<button class="btn">button 1</button>
<p class="msg"></p>
</div>
<div>
<button class="btn">button 2</button>
<p class="msg"></p>
</div>
<div>
<button class="btn">button 3</button>
<p class="msg"></p>
</div>
If I click Button1, the text should be displayed underneath Button1, if I click Button2 text should be displayed underneath Button2, and so on...

closestThe
.msgelement is next to thebuttonnot on of its parents, so you can get the parent element of the button which is thediv, and then usequerySelectorinto it to get the.msgelement.