user1915308
user1915308

Reputation: 364

Change the href link of an anchor with the text using jquery

if I have:

<a href="#">Title </a> 
<a href="#">Title2 </a> 

I want on the first anchor the href to be Title and on the second one Title2

I've tried using the attr("href" function() { return this.text; });

Upvotes: 0

Views: 1764

Answers (2)

Brad Christie
Brad Christie

Reputation: 101594

Changing it would be something like:

$('a').each(function(i,e){
  this.href = '#' + $(this).text(); // using # because i assume named anchor?
});

That would change:

<a href="#">Title</a>        -> <a href="#Title">Title1</a>
<a href="#">Title2</a>       -> <a href="#Title2">Title2</a>
  • Grab all anchors ($('a'))
  • Loop through each one (.each())
  • Assign a new value using the anchor's text (this.href = $(this).text())

You can also remove the '#' + portion from above if you don't want a link to a named anchor/id element, but chances are anything that's being supplied by the anchor's display text isn't going to be a valid URL)

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

Almost there :

$('a').attr("href", function() { return $(this).text(); });

Demonstration

Upvotes: 3

Related Questions