Using $(this) after .replaceWith()
Asked Answered
T

3

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());
    });
});
Toowoomba answered 9/12, 2010 at 14:42 Comment(0)
K
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());
    });
});
Kazimir answered 9/12, 2010 at 14:47 Comment(0)
E
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());
  });
});
Evidentiary answered 9/12, 2010 at 14:53 Comment(0)
S
0

Try this:

alert($(this).replaceWith('<p>New Paragraph</p>').text());
Sniffle answered 9/12, 2010 at 14:44 Comment(2)
This won't work, .replaceWith() returns the previous object, the <a>, not the <p> it replaced it with.Kazimir
That doesn't work. The replaceWith method returns the original jQuery object with the original element, not a new jQuery object with the new element. api.jquery.com/replaceWithEvidentiary

© 2022 - 2024 — McMap. All rights reserved.