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...
The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
The .msg
element is next to the button
not on of its parents, so you can get the parent element of the button which is the div
, and then use querySelector
into it to get the .msg
element.
let btn = document.querySelectorAll('button');
btn.forEach(function(i) {
i.addEventListener('click', function() {
const parentDiv = i.parentElement;
parentDiv.querySelector('.msg').innerHTML = i.innerHTML;
});
});
<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>