There are several identical blocks with a header and a button under it tell me how to copy the header to input when the button is pressed. How do I handle multiple buttons and headers?
if there is only one header then this code works
const modalTitle = document.querySelector('.popup_wrap>h3');
const modalBtn = document.querySelector('.popup-btn');
const resInp = document.querySelector('.research-title');
modalBtn.addEventListener('click', function(e) {
resInp.value = modalTitle.innerHTML;
});
<div class="popup_wrap">
<h3>Title</h3>
<a class="popup-btn" data-modal="5">Click</a>
</div>
<div class="popup_wrap">
<h3>Title2</h3>
<a class="popup-btn" data-modal="5">Click</a>
</div>
3
Answers
try to create a function and call it on button click like the code below
here is the modified code hope it will help you :
Explanation :
The copy function takes an header_id parameter, which represents the ID of the header element to be copied.
Inside the function, the header element is selected using document.getElementById(id).
The resInp variable is selected using document.querySelector(‘.research-title’) outside the copy function, assuming the input field with the class research-title exists on the page.When the button is clicked, the copy function is called with the corresponding header ID as an argument. The function retrieves the header element and assigns its innerHTML value to the resInp input field’s value property, effectively copying the header text to the input field.
You can do like this:
previousElementSibling
gets the precedent node at the same level inside the parent.If you have nodes in between you can repeat the process until you find a
h3
. (Or usethis.parentElement.querySelector('h3')
as suggested in a comment)This is a fool proof version for as many dynamically added elements without the need of ids or named function, as long as the js code runs after the elements are added.