fmourtaza
fmourtaza

Reputation: 307

Get collection of Href

I am getting the below html using this code:

$(".ms-rtestate-field")[0];

and here is the return

<div class="ms-rtestate-field" dir=""> 
<a href="/DE/Company/OurOrganisation/ActionsDE.pdf">DE</a> 
<a href="/EN/Company/OurOrganisation/Act‌​ionsEN.pdf">EN</a> 
</div> 

How to get the hrefs of all the anchors in the div where some divs may list many anchors? trying this one but not good

$(".ms-rtestate-field")[0].attr(""href);

Upvotes: 1

Views: 183

Answers (4)

Rayon
Rayon

Reputation: 36609

Use .map, Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

Array.from() method creates a new Array instance from an array-like or iterable object.

var href = $('.ms-rtestate-field').find('a[href]').map(function() {
  return this.href;
}).get();
console.log(href);
//OR
var href = Array.from($('.ms-rtestate-field').find('a[href]')).map(function(elem) {
  return elem.href;
});
console.log(href);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="ms-rtestate-field" dir="">
  <a href="/DE/Company/OurOrganisation/ActionsDE.pdf">DE</a> 
  <a href="/EN/Company/OurOrganisation/Act‌ionsEN.pdf">EN</a> 
</div>

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34150

Create an array and add hrefs to it.

var hrefs = [];

$(".ms-rtestate-field a").each(function(){
  hrefs.push($(this).attr("href"));
});

Now you can access them like:

for(var i=0;i<hrefs.length;i++)
    alert(hrefs[i]);

Upvotes: 3

Dhara Parmar
Dhara Parmar

Reputation: 8101

$(".ms-rtestate-field a").each(function(){
var href = $(this).attr("href");
});

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

How to get the First href and second href ?

make it

var firstHREF = $(".ms-rtestate-field a:eq(0)").attr("href");
var secondHREF = $(".ms-rtestate-field a:eq(1)").attr("href");

You need to go one level below to the specific anchor a based on its index using eq selector.

If you want the array of hrefs then simply

var hrefs = [];
$(".ms-rtestate-field a").each(function(){
  hrefs.push( $(this).attr( "href" ) );
});

Upvotes: 0

Related Questions