9

Please consider the below HTML and Javascript. In the script, I am replacing an a tag with a p tag. I am expecting the alert() function to return the contents of the p tag but instead it returns the contents of the original a tag which no longer exists.

How can I reference the new element?

HTML:

<a href="">This is a link</a>

Javascript:

$(document).ready(function() {
    $("a").each(function() {
        $(this).replaceWith('<p>New Paragraph</p>');
        alert($(this).text());
    });
});
GateKiller
  • 74,180
  • 73
  • 171
  • 204

3 Answers3

11

You can't do it directly with .replaceWith(), but you can create it separately. Try this:

$(document).ready(function() {
    $("a").each(function() {
        var p = $('<p>New Paragraph</p>');
        $(this).replaceWith(p);
        alert(p.text());
    });
});
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
2

You can use the replaceAll method instead, which returns the new content instead of the original content:

$(document).ready(function() {
  $("a").each(function() {
    alert($('<p>New Paragraph</p>').replaceAll($(this)).text());
  });
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Try this:

alert($(this).replaceWith('<p>New Paragraph</p>').text());
Sidharth Panwar
  • 4,606
  • 6
  • 27
  • 36