Question

I want to use JQuery to replace the html of and element with my own. I thought I would just be able to use:

$('#nav a:contains(replace me)').replaceWith('<h2>Label</h2>');

but this does not work. I have tried many variations of this to no avail.

Would anyone know what I am doing wrong?

EDIT: Added current html:

<div id="nav">
<a href="#">replace me</a>
<a href="#">this is ok</a>
<a href="#">this is ok</a>
<a href="#">this is ok</a>
</div>

What I want it to look like:

<div id="nav">
<a href="#"><h2>Label</h2></a>
<a href="#">this is ok</a>
<a href="#">this is ok</a>
<a href="#">this is ok</a>
</div>
Was it helpful?

Solution

I think I'd just do:

$('#nav a').html(function(i, html) {
    return $.trim(html) == 'replace me' ? '<h2>Label</h2>' : html;
});

FIDDLE

as I'm not very fond of :contains, or

$('#nav a:contains(replace me)').html('<h2>Label</h2>');

FIDDLE

as replaceWith() will replace the entire anchor and not just it's content.

OTHER TIPS

may be it's help for you

   $("div").find('a').each(function(index)
    {
        if(index==0){
         $(this).html("<h2>Label</h2>");
        }

    }); 
$("a").text(function () {
    return $(this).text().replace("replace me", "<h2>Label</h2>"); 
});

here's a jsfiddle link http://jsfiddle.net/xpfRV/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top