0

I want to find and "console.log" every src value in an HTML page that has a certain text; for example (dam/etc/vsvs). Is it possible to do it with javascript and in the console, as I'm not able to reach to source code of the page? I'm not a developer just trying to find the images I want and list them.

Any help will be appreciated.

Thanks in advance.

t-bay
  • 15
  • 3

1 Answers1

0

As far as I understand, you have an HTML page and you need to grab every src value which meets some expectations (i.e. starts with smth, includes smth).

So, if you are able to run a script on the page then you can recursively go node by node and check if it has an src attribute.

const findSrc = (node) => {
  const attributesToCheck = ['src', 'srcset', 'data-srcset']

  const srcs = attributesToCheck.map(name => {
    const attr = node.getAttribute(name)

    // here is a condition for your match
    return attr?.startsWith("/etc") ? attr : false
  }).filter(Boolean)

  if (node.children) {
    return srcs.concat(Array.from(node.children).flatMap(findSrc));
  }

  return srcs;
};

console.log(findSrc(document.body));
Ivan Burnaev
  • 2,690
  • 18
  • 27
  • Thank you so much Ivan, it definitly work like that const findSrc = (node) => { const src = node.getAttribute("src"); // here is a condition for your match const srcs = src?.indexOf("/etc") ? [src] : []; if (node.children) { return srcs.concat(Array.from(node.children).flatMap(findSrc)); } return srcs; }; console.log(findSrc(document.body)); If I can ask for a little favor here, I also would like to search for attributes like "srcset", "data-srcset". Is there a way to search for all in the same code? – t-bay Feb 09 '22 at 13:30
  • yeah, sure... Updated my initial answer. You can specify a list of attributes to check. – Ivan Burnaev Feb 09 '22 at 13:52
  • Thank you again Ivan, now I'm only getting negative/positive numbers in the console, I guess it's because of the .filter(Boolean)? I already tried changing it to .filter(String) but only get undefined outputs. Is there a way that I can get values like the initial code? – t-bay Feb 09 '22 at 14:04
  • Oh, so sorry about that. Yeah, there was a mistake in the `map` function. Updated my initial answer once again. – Ivan Burnaev Feb 09 '22 at 18:20