简体   繁体   中英

How to get value inside div inside ul inside li with Javascript?

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" class="filter-list-cell filter-text css-ahhuez">
            <span class="dog-123" title="dogname">TEDDY</span>
            <span>8%</span>
        </div>
    </li>
    <li style="position: absolute;">
        <div role="checkbox" class="filter-list-cell filter-text css-voqwhr">
            <span class="dog-123" 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!

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 class="dog-123">TEDDY</span> <span>8%</span> </li> <li> <span class="dog-123">OZZY</span> <span>7%</span> </li> <li> <span class="dog-123">Bob from Accounting</span> <span>700%</span> </li> </ul>

Additional documentation

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 apseudo-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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM