Skip to content

Why does jQuery select only one element when chaining .attr() in selector?

I have a simple list of links:

  <li><a href="1">link 1</a></li>
  <li><a href="2">link 2</a></li>
  <li><a href="3">link 3</a></li>
  <li><a href="4">link 4</a></li>
  <li><a href="5">link 5</a></li>
  <li><a href="6">link 6</a></li>
  <li><a href="7">link 7</a></li>
  <li><a href="8">link 8</a></li>
  <li><a href="9">link 9</a></li>
  <li><a href="10">link 10</a></li>

How do I select these links with jQuery?

$('a') – this returns all the links

How do I get all the contents of these links (“link 1”, “link 2”, “link 3″…)?


How do I get all the hrefs from the links (1, 2, 3…)?


NOT TRUE ^ IT SELECTS ONLY THE FIRST LINK and returns 1 instead of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

I know I could map, do each etc. but I’m writing a crawler that uses this a lot and wondered why is this happening and whether I can get all the hrefs without any loops here, just using jQuery’s (preferably jQuery core) selectors?



You can’t really loop over DOM elements without, well, looping through them.

Looping won’t have any dramatic effect on the performance of your web-crawler.

This being said, you’re just looking at:

$('a').each(function() {