Categories
JavaScript Answers

How to extract anchor text and URL from anchor tags with JavaScript?

Spread the love

Sometimes, we want to extract anchor text and URL from anchor tags with JavaScript

In this article, we’ll look at how to extract anchor text and URL from anchor tags with JavaScript.

How to extract anchor text and URL from anchor tags with JavaScript?

To extract anchor text and URL from anchor tags with JavaScript, we can set the string as the innerHTML of an element.

For instance, we write:

const str = `
  <a href="http://yahoo.com">Yahoo</a>
  <a href="http://google.com">Google</a>
`
const div = document.createElement('div')
div.innerHTML = str
const anchors = div.querySelectorAll('a')
const arr = [...anchors].map((a) => {
  const {
    textContent,
    href
  } = a
  return {
    textContent,
    href
  }
})
console.log(arr)

to create a div, set the innerHTML of the div to the str` string, and then get the values by selecting the anchors.

To do this, we call createElement to creatr the div.

Then we set div.innerHTML to str to populate the div with the anchors.

Next, we select the anchors with div.querySelectorAll.

And then we spread the anchors into an array and call map to return the properties we’re looking for.

textContent has the anchor text and href has the link’s URL.

Therefore, arr is

[{
  href: "http://yahoo.com/",
  textContent: "Yahoo"
}, {
  href: "http://google.com/",
  textContent: "Google"
}]

Conclusion

To extract anchor text and URL from anchor tags with JavaScript, we can set the string as the innerHTML of an element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *