Search code examples
javascriptjquerycssnodelist

How to get a list of values from a specific CSS Selector


I want to retrieve at once a list of values from a spcific CSS selector.

I want to extract the text in <strong> only. I am using :

document.querySelectorAll("p > strong")

But the I got a Node list...

NodeList(101) [strong, strong, strong, strong, strong, strong, strong, strong, strong,...]

I am targeting the innerText like :

document.querySelectorAll("p > strong")[1].innerText

How can I extract all the targeted text values in a list at once ?


Solution

  • Use the spread operator to turn it into an array and then use the map method to get what you need.

    var array = [...document.querySelectorAll("p > strong")].map(a=>a.innerText);
    
    console.log(array);
    <p><strong>I</strong></p>
    <p><strong>heart</strong></p>
    <p><strong>To</strong></p>
    <p><strong>Fart</strong></p>