extract text inside <li> tag using java script or jquery

Issue

var array1[] ;

//i want to store text inside href in a array like this
// [cat,dog,cow,hen,elephant] , how can I do that?
<div class="ABCD"><h2 class="AB">Tags</h2>
<ul>
 <li><a href="/example">cat</a></li>
 <li><a href="/example2">dog</a></li>
 <li><a href="/example3">cow</a></li>
 <li><a href="/example4">hen</a></li>
 <li><a href="/example5">elephant</a></li>
</ul>
</div>

I want to get cat,dog,cow,hen,elephant to array animals[] using javascript.

how can I get them to a array? please help

Solution

Please refer below for the requirement you are looking for

let allLinks = document.querySelectorAll("div.ABCD  li > a")

let allLinksarray = Array.from(allLinks).map(linkElem => linkElem.innerHTML)

console.log(allLinksarray)
<div class="ABCD">
  <h2 class="AB">Tags</h2>
  <ul>
    <li><a href="/example">cat</a></li>
    <li><a href="/example2">dog</a></li>
    <li><a href="/example3">cow</a></li>
    <li><a href="/example4">hen</a></li>
    <li><a href="/example5">elephant</a></li>
  </ul>
</div>

Hope this helps.

Answered By – Nithish

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.