Search code examples
jquerygoogle-chrome-extensionundefinedhref

Getting the text of a link with jQuery


So I'm trying to develop my own extension for Chrome. For a first try, I want to create an extension that gathers all the links in the page into one place.
Since I don't know what kind of links there are, I have to get the link href and link text by selecting their attributes.
The link href attribute selector worked fine, but I can't seem to get the link text using my code. It always returns undefined. Here's my code:
$("a[href^='http']").eq(i).innerHTML
(i is the variable in a for loop, just pretend it's some number)
$("a[href^='http']").eq(i) should return the element, right? So what am I missing?

Here's a snippet to show you what I mean:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body><a href="https://www.google.com/">link1</a><a href="https://www.google.com/">link2</a><a href="https://www.google.com/">link3</a>
</body>
<p id="log">Pretend this is the console: </p>
<script>
  for (var i = 0; i < document.links.length; i++) {
    document.getElementById("log").innerHTML += ($("a[href^='http']").eq(i).attr("href") + " (" + $("a[href^='http']").eq(i).innerHTML + ") / ");
  }
</script>

</html>


Solution

  • innerHTML is a method, not a property, use it like so: $("a[href^='http']").eq(i).innerHTML()

    To clarify, the .eq(i) method returns not a DOMElement, but a jQuery object. jQuery objects have the innerHTML() method - which returns a string of the html inside the element referred to by the jQuery object.

    On a side note - seeing as you are looking to get the text, not html, maybe you actually would be better off using the .text() method instead?