Albert
Albert

Reputation: 507

Grab the href and text of <a> tags from the page

I have a page with multiple links (<a> tag with a specific class-selector, e.g. "class=my-link"), I need to grab the text of these links (the content between <a> and </a> tags) and their "href" attribute and output it into a JavaScript multidimensional object, giving an ID number (just increment, 01, 02, 03 and so on).

Example.

Original page with links:

<a href="red" class="my-link">Apples are red</a>
<a href="green" class="my-link">Grass is green</a>

Output:

var mylinks = [
  { "LinkID": "01", "LinkHref": "red", "LinkText": "Apples are red" },
  { "LinkID": "02", "LinkHref": "green", "LinkText": "Grass is green" }
];

Upvotes: 1

Views: 219

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

You can do something like following

var arr = [];
$.each( $("a.my-link"), function( i, element ) { // iterate over all anchor elements with class my-link
   arr.push({
       "LinkID" : i+1,
       "LinkHref" : $(element).attr("href"),
       "LinkText" : $(element).html()
   });
});

Upvotes: 2

Related Questions