simple
simple

Reputation: 2397

Loop through all links and find the href

This is only finding the first link. Why is it not looping through all of the links?

http://jsfiddle.net/infatti/7r4fV/

var alertHref = $('#myLinks').find('a').attr('href');

$('#myDivs').find(alertHref).css('background-color', 'yellow');

<span id="myLinks">
  <a href="#div1">link 1</a>
  <a href="#div2">link 2</a>
</span>
<hr />
<div id="myDivs">
  <div id="div1">div 1</div>
  <div id="div2">div 2</div>
</div>

Upvotes: 0

Views: 2289

Answers (2)

vol7ron
vol7ron

Reputation: 42099

use jQuery.each to loop through more than one.

Using your Fiddle:

var $hrefs  = $('#myLinks').find('a[href]');
var $myDivs = $('#myDivs');

$hrefs.each(function(index,link){
   $(link.hash,$myDivs).css('background-color','yellow');
});

You could also use map (fiddle):

var hrefs  = $('#myLinks').find('a[href]')
                          .map(function(){ return this.hash; })
                          .get();

$('#myDivs').find(hrefs.join(',')).css('background-color','yellow');

Upvotes: 1

Jason P
Jason P

Reputation: 27012

find('a') returns a list of all the a elements, but .attr('href') returns the href of the first link only.

You need to loop through the a elements:

http://jsfiddle.net/Gj2R9/

$('#myLinks a').each(function() {
    $($(this).attr('href')).css('background-color', 'yellow');
});

Upvotes: 2

Related Questions