0

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; });

Ram
  • 143,282
  • 16
  • 168
  • 197
user1915308
  • 354
  • 4
  • 12
  • Possbible duplicate of http://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery – Sam Jan 02 '13 at 15:33

2 Answers2

3

Almost there :

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

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • +1, good use of using the second parameter as a function. (OP started with it, but I still wasn't aware `attr` worked like native `.replace` does with passing a function) – Brad Christie Jan 02 '13 at 15:37
  • @BradChristie It's a jQuery thing, if you notice almost all of them are able to do this not just `attr`. You can even do it with CSS: `$('a').css('background', function () { **whatever** });` – Mark Pieszak - Trilon.io Jan 02 '13 at 15:43
  • 1
    @mcpDESIGNS: I don't disagree; and it's more like jQuery implemented it with the original methods like `replace` in mind to keep consistency. – Brad Christie Jan 02 '13 at 15:46
1

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)

Brad Christie
  • 100,477
  • 16
  • 156
  • 200