Skip to content

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

I have a simple list of links:

<ul>
  <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>
</ul>

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″…)?

$('a').text()

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

$('a').attr('href')

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?

Demo: https://jsfiddle.net/z5j1ty08/

Answer

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() {
  console.log($(this).text());
});

Demo: https://jsfiddle.net/q1er5946/