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 >
<i id="update_pen" onclick="update_function()"></i> <--- click here
<div id="swiper-slide-one">
<div >
<h4 >
<a href="service-details.html">Hello</a> <---- this text
</h4>
<div id="text_area_box">
<input type="text" name="" required="">
<label>Titre</label>
</div>
</div>
</div>
</div>
CodePudding user response:
- Use
addEventListener()
to bind your handler so that you can get a reference to the element from the Event that's raised, not an outdatedonclick
attribute. - Use
closest()
to get the nearest.swiper-slide
element. - Use
querySelector()
to get the childa
element. - 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);
const input = parent.querySelector('input');
input.value = text;
});
});
<div >
<i >Click</i>
<div >
<div >
<h4 >
<a href="service-details.html">Hello</a>
</h4>
<div >
<input type="text" name="" required="" />
<label>Titre</label>
</div>
</div>
</div>
</div>
<div >
<i >Click</i>
<div >
<div >
<h4 >
<a href="service-details.html">Goodbye</a>
</h4>
<div >
<input type="text" name="" required="" />
<label>Titre</label>
</div>
</div>
</div>
</div>
CodePudding user response:
You can give an id to the element you want to store:
<a id="hello" href="service-details.html">Hello</a>
Declare a variable const variable = ""
And then you can use
variable = document.getElementById("hello").innerHTML
in your button function in order to store the contents