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'));
});
Matt Ball
2010-10-20 22:14:09
Rather than use find, why not let sizzle do what it does best and use `$('p a')`
Phil Brown
2010-10-20 22:16:07
@Phil: because they're semantically equivalent, but `.find()` is faster.
Matt Ball
2010-10-20 22:17:51
@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
2010-10-20 22:18:24
Thanks guys, learn something new every day
Phil Brown
2010-10-20 22:27:40
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
2010-10-20 22:39:40
+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
2010-10-20 22:16:06
it only replaces few of the anchors and leave others. it shows an error : fragment.childNodes is undefined
Yassir
2010-10-20 23:06:04
@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
2010-10-20 23:22:35
+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"><span>Test</span></a>
gracefully degrades for non-CSS3 browsers.
jnpcl
2010-10-20 22:21:42
Doesn't appear as though the `:after` pseudo selector is supported before IE9. http://www.quirksmode.org/css/contents.html#t15
patrick dw
2010-10-20 22:28:40