J
J
js_forever2020-05-10 00:54:29
JavaScript
js_forever, 2020-05-10 00:54:29

Get the text of a link knowing the link?

Good afternoon!
Interested in pure JS code that allows you to quickly and elegantly return the link text.
For example, we have a link in an arbitrary place in the html code of the page: <a href="http://habr.com">Хабр</a>
Knowing the link http://habr.com, you need to return the link text to the variable, in this case "Habr".

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-05-10
@js_forever

function getLinkText (href) {
  return [...document.getElementsByTagName('a')]
    .filter(el => el.getAttribute('href') === href)
    .map(el => el.innerText)
}

O
Oleg, 2020-05-10
@politon

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question