How to fetch a specific span tag on a webpage using Chrome console?

20 Views Asked by At

I'm on a website and I'd like to fetch a list of a specific span.

Ex. Names1

How do I get the list of all the Names1 (each name on a new line), using the Google Chrome Console ?

Thank you very much for your help

Everything I tried came back with an error message (some saying that the span was undefined etc.) I've tried:

var spanElements = document.querySelectorAll('span._ap3a._aaco._aacw._aacx._aad7._aade');

    // Initialize an empty array to store the names
    var namesList = [];

    // Loop through each <span> element and add its content to the names list
    spanElements.forEach(function(span) {
        namesList.push(span.textContent);
    });

    // Log the names list
    console.log(namesList);
});

it came back "undefined"
1

There are 1 best solutions below

0
Carsten Massmann On

Assuming that you require only one class name to be present on a <span> element for it to qualify as a "name"-span the following should do what you want:

const classes="_ap3a._aaco._aacw._aacx._aad7._aade".split("."),
  names=[...document.querySelectorAll('span')]
   .filter(el=>classes.some(cl=>el.classList.contains(cl)))     
   .map(el=>el.textContent);
console.log(names.join("\n"));
This is <span class="red _ap3a">Henry</span> 
and this is <span class="green _aaco">Susan</span>. 
And then there are <span class="_aacx blue">Claire</span>,
<span class="_aad7 _aacw">Anne</span>
and <span class="_aade">Tom</span>.
And this is not a name: 
<span class="noname">not-a-name</span>