0

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 ?

j08691
  • 204,283
  • 31
  • 260
  • 272
B4b4j1
  • 430
  • 2
  • 7
  • 24
  • 1
    Tagged [tag:jquery] so: `$("p>strong").map((i,e) => $(e).text()).toArray()` (not provied as an answer as it doesn't look like you *actually* want jquery. – freedomn-m Sep 09 '21 at 14:24

2 Answers2

1

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>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
1

Your code works if you loop over the nodeList you have

I use textContent though - same thing but more standard

const strong = document.querySelectorAll("p > strong")
const texts = []
for (let i = 0; i< strong.length;i++) texts.push(strong[i].textContent)
console.log(texts)
<p>Here is some <strong>text</strong> and some <strong>more text</strong></p>

Alternatively but slower (if that matters) map the nodelist after casting to array using spread syntax

const texts = [...document.querySelectorAll("p > strong")]
  .map(({textContent}) => textContent)
console.log(texts)
<p>Here is some <strong>text</strong> and some <strong>more text</strong></p>

jQuery if you need

const texts = $("p strong").map((_,e) => e.textContent).get();
console.log(texts)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>Here is some <strong>text</strong> and some <strong>more text</strong></p>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    `textContent` and `innerText` are not the same, nor is one *more standard* than another. `innerText` only shows rendered text whereas `textContent` would show the CSS or Javascript code of a ` – I wrestled a bear once. Sep 09 '21 at 14:49
  • https://stackoverflow.com/questions/35213147/difference-between-textcontent-vs-innertext – mplungjan Sep 09 '21 at 14:56
  • Being standardized earlier doesn't make it "more standard." – I wrestled a bear once. Sep 09 '21 at 15:01