1

enter image description here

I want to extract all the emails from this HTML document. There are several entries. Each entry starts with a div and several span elements and the one having the email has the <a tag and has an href="mailto:abc@gmail.com"
How can I use javascript to loop over and extract the href value for all these

juan
  • 47
  • 7
  • 3
    Did you attempt anything? – epascarello Mar 10 '23 at 13:47
  • Does this answer your question? [Get local href value from anchor (a) tag](https://stackoverflow.com/questions/15439853/get-local-href-value-from-anchor-a-tag) – Solomon Ucko Mar 10 '23 at 13:49
  • 1
    `document.querySelectorAll`, in combination with an _attribute selector_ that selects only elements that have a href attribute starting with `mailto:` ... – CBroe Mar 10 '23 at 13:49
  • Look this [How to use querySelector with an anchor tag with href?](https://stackoverflow.com/questions/48239329/how-to-use-queryselector-with-an-anchor-tag-with-href) – salsan Mar 10 '23 at 13:54

2 Answers2

1
  • Use a starts with selector to match the anchors.
  • Loop over the anchors
  • Read the href
  • Split it at the : and get the email

const emails = [...document.querySelectorAll('a[href^="mailto:"]')].map(({href}) => href.split(":")[1]);
console.log(emails);
<a href="//example.com">a</a>
<a href="mailto:foo@example.com">a</a>
<a href="mailto:bar@example.com">a</a>
<a href="mailto:baz@example.com">a</a>
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

With querySelector you can fetch the anchor tag. Afterwards you can get the content from the href attribute. And then you have to extract the email after mailto:. You can do that with regex or with the simple split() function.

const mail = document.querySelector('a[href^="mailto:"]').getAttribute('href').split(":")[1];

console.log(mail)
<a class="p48xx " href="mailto:test@test.com">mail</a>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79