tags:

views:

52

answers:

4

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.

+1  A: 

Try this:

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

Demo

Matt Ball
Rather than use find, why not let sizzle do what it does best and use `$('p a')`
Phil Brown
@Phil: because they're semantically equivalent, but `.find()` is faster.
Matt Ball
@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
Thanks guys, learn something new every day
Phil Brown
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
+7  A: 

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
@Felix, I was typing this answer! You're a speed demon.
Jacob Relkin
Definitely cleaner than my answer. +1
Matt Ball
+1 for simplicity
xPheRe
+1 for making me notice the `.replaceWith()` method.
Peter Ajtai
it only replaces few of the anchors and leave others. it shows an error : fragment.childNodes is undefined
Yassir
@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
+1  A: 

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"&gt;&lt;span&gt;Test&lt;/span&gt;&lt;/a&gt;

gracefully degrades for non-CSS3 browsers.

jnpcl
Doesn't appear as though the `:after` pseudo selector is supported before IE9. http://www.quirksmode.org/css/contents.html#t15
patrick dw
A: 

Pretty similar, I know...

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