0

i have a p tag that has many anchor tags and some text. i want to replace each of the anchor tags with its respected href.

Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112

4 Answers4

7

I interpret your question that you want to replace the whole tag, not only the contained text, like so: http://jsfiddle.net/xXmWj/1/

You are looking for .replaceWith():

$('p a').replaceWith(function() {
    return $(this).attr('href');
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @Felix, I was typing this answer! You're a speed demon. – Jacob Relkin Oct 20 '10 at 22:17
  • Definitely cleaner than my answer. +1 – Matt Ball Oct 20 '10 at 22:18
  • it only replaces few of the anchors and leave others. it shows an error : fragment.childNodes is undefined – Hannoun Yassir Oct 20 '10 at 23:06
  • @Yassir: Could you please show this part of your HTML? Could it be that some anchors have no `href` attribute? You might try changing the selector to `$('p a[href]')` and/or changing the return value to: `document.createTextNode($(this).attr('href'));`. Unfortunately I don't know what this error means in this context. – Felix Kling Oct 20 '10 at 23:22
1

Try this:

$('p').find('a').each(function ()
{
    var $this = $(this);
    $this.html($this.attr('href'));
});

Demo

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Rather than use find, why not let sizzle do what it does best and use `$('p a')` – Phil Oct 20 '10 at 22:16
  • 1
    @Phil: because they're semantically equivalent, but `.find()` is faster. – Matt Ball Oct 20 '10 at 22:17
  • 1
    @Phil: `$("p a")` pretty much gets translated into `$("p").find("a")`. See http://stackoverflow.com/questions/3177763/what-is-the-fastest-method-for-selecting-descendant-elements-in-jquery – Marko Oct 20 '10 at 22:18
  • This doesn't replace the `a` tag with the contents of the `href` attribute. It just sets the `innerHTML` of the `a` tag to the `href`.... not the same thing.... the `a` tags are not replaced like asked for in the OP. – Peter Ajtai Oct 20 '10 at 22:39
1

CSS3 solution without using jQuery:

<style type="text/css">
    a > span { display: none; }
    a:after { content: attr(href); }
</style>
<a href="http://www.test.com"><span>Test</span></a>

gracefully degrades for non-CSS3 browsers.

drudge
  • 35,471
  • 7
  • 34
  • 45
  • Doesn't appear as though the `:after` pseudo selector is supported before IE9. http://www.quirksmode.org/css/contents.html#t15 – user113716 Oct 20 '10 at 22:28
0

Pretty similar, I know...

$("a").each(function(){
  $(this).text($(this).attr('href'));
});
teampoop
  • 11
  • 2