Home > Mobile >  How to get value inside div inside ul inside li with Javascript?
How to get value inside div inside ul inside li with Javascript?

Time:05-12

I'm not learning jQuery yet, so javascript please. here is the HTML like below

<ul style="position: absolute;">
    <li style="position: absolute;">
        <div role="checkbox" >
            <span  title="dogname">TEDDY</span>
            <span>8%</span>
        </div>
    </li>
    <li style="position: absolute;">
        <div role="checkbox" >
            <span  title="dogname">OZZY</span>
            <span>7%</span>
        </div>
    </li>
    .
    .
    .
    8 more <li>
</ul>

what i try to get is inside the li > span value "TEDDY" and next li > span "OZZY" and the rest of 8 more li value inside the span, make the result as a array like:

dogname = [TEDDY,OZZY,REX...]

i tried right click to copy selector path then use document.querySelectorAll(), i got 10 NodeList, i Array.from it but i still need to pass the div to get the span value.

i think i should loop through them? but it looks weird to me... im not really familiar with html so please give me some hint or direction for this problem

Thanks!

CodePudding user response:

Grab the dogs by the dog-123 class name, and then map over the (converted to an array) node list to create a new array of names from each node's text content.

const dogs = document.querySelectorAll('.dog-123');
const names = [...dogs].map(dog => dog.textContent);
console.log(names);
<ul>
  <li>
    <span >TEDDY</span>
    <span>8%</span>
  </li>
  <li>
    <span >OZZY</span>
    <span>7%</span>
  </li>
  <li>
    <span >Bob from Accounting</span>
    <span>700%</span>
  </li>
</ul>

Additional documentation

CodePudding user response:

You can do it by using CSS selectors: grab the first span inside every div which is inside a li which is inside an ul. The :first-child part is called a pseudo-class, that is, it selects an element with respect not only to itself and its parents / siblings, but against characteristics of the XML tree or even external characteristics such as browser history.

Careful, though, because if you have another ul whose descendants have those characteristics, you would be selecting undesired values.

In one line:

Array.from(document.querySelectorAll("ul > li > div span:first-child")).map(x => x.innerText);

If you wanted to be more precise (in a scraper, for example), you would probably start with a root element with a known id (thence unique). So let's say you have <ul id="myList">, then the CSS selector would be #myList > li > div span:first-child.

  • Related