Home > Software engineering >  How can i get the text of an element on html using Family properties?
How can i get the text of an element on html using Family properties?

Time:10-16

I wanna get the text on an element using family properties with javascript function, one of these (firstChild, nextSibling , parent...)

  1. i click on button .
  2. get the text from the <a>Hello</a> element which is Hello
  3. 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:

  1. Use addEventListener() to bind your handler so that you can get a reference to the element from the Event that's raised, not an outdated onclick attribute.
  2. Use closest() to get the nearest .swiper-slide element.
  3. Use querySelector() to get the child a element.
  4. 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

  • Related