Languages
[Edit]
EN

JavaScript - get link text (or content)

0 points
Created by:
AnnLen
15120

In this article, we would like to show you how to get link text using JavaScript​​​​​​.

Quick solution:

// ONLINE-RUNNER:browser;

<a id="link" href="https://some-domain.com">Some domain</a>
<script>

  var link = document.querySelector('#link');

  console.log(link.text);			// available only in Anchor HTML Element (<a> element) 
  console.log(link.innerText);		// available for each HTML Element (Element extends Node)
  console.log(link.innerHTML);		// available for each HTML Element (Element extends Node)
  console.log(link.textContent);	// available for each Node

</script>

 

Practical example

In this example, we use four different methods to get the text from the a element.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
  <a id="link" href="https://some-domain.com">Some domain</a>
  <script>

    var link = document.querySelector('#link');

    console.log(link.text);			// available only in Anchor HTML Element (<a> element) 
    console.log(link.innerText);	// available for each HTML Element (Element extends Node)
    console.log(link.innerHTML);	// available for each HTML Element (Element extends Node)
    console.log(link.textContent);	// available for each Node

  </script>
</body>
</html>

Output:

Some domain
Some domain
Some domain
Some domain

References

  1. Node.textContent - Web APIs | MDN
  2. HTMLElement.innerText - Web APIs | MDN
  3. Element.innerHTML - Web APIs | MDN
  4. <a>: The Anchor element - HTML: HyperText Markup Language | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join