I wanna get the text on an element using family properties with javascript function, one of these (firstChild, nextSibling , parent…)
- i click on button .
- get the text from the
<a>Hello</a>element which is
Hello - store the text on a variable
<div class="swiper-slide">
<i class="fa-regular fa-pen-to-square" id="update_pen" onclick="update_function()"></i> <--- click here
<div class="services-item mb-40 elementor-repeater-item-78d8e80" id="swiper-slide-one">
<div class="services-item__content">
<h4 class="services-item__tp-title mb-30">
<a href="service-details.html">Hello</a> <---- this text
</h4>
<div class="text_area_box" id="text_area_box">
<input type="text" name="" required="">
<label>Titre</label>
</div>
</div>
</div>
</div>
>Solution :
- Use
addEventListener()to bind your handler so that you can get a reference to the element from the Event that’s raised, not an outdatedonclickattribute. - Use
closest()to get the nearest.swiper-slideelement. - Use
querySelector()to get the childaelement. - Read its
textContent
Also, given the context and purpose of the question, I assume the HTML structure is repeated multiple times. As such you need to remove the id attributes from all elements that are repeated as id must be unique within the DOM.
document.querySelectorAll('i.button').forEach(el => {
el.addEventListener('click', e => {
const parent = e.target.closest('.swiper-slide');
const text = parent.querySelector('a').textContent;
console.log(text);
});
});
<div class="swiper-slide">
<i class="button fa-regular fa-pen-to-square">Click</i>
<div class="services-item mb-40 elementor-repeater-item-78d8e80">
<div class="services-item__content">
<h4 class="services-item__tp-title mb-30">
<a href="service-details.html">Hello</a>
</h4>
<div class="text_area_box">
<input type="text" name="" required="" />
<label>Titre</label>
</div>
</div>
</div>
</div>
<div class="swiper-slide">
<i class="button fa-regular fa-pen-to-square">Click</i>
<div class="services-item mb-40 elementor-repeater-item-78d8e80">
<div class="services-item__content">
<h4 class="services-item__tp-title mb-30">
<a href="service-details.html">Goodbye</a>
</h4>
<div class="text_area_box">
<input type="text" name="" required="" />
<label>Titre</label>
</div>
</div>
</div>
</div>