Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $(this) after .replaceWith()

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());
    });
});
like image 371
GateKiller Avatar asked Dec 09 '10 14:12

GateKiller


People also ask

How to replaceWith in jQuery?

The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.

How can I replace all characters in a string using jQuery?

The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements. Parameters: This method accepts two parameter as mentioned above and described below: content: It is the required parameter which is used to specify the content to insert.

How do you replace HTML?

Use . replace() method on HTML element and replace it with the new HTML Document(eg.. $('html'). html(Str)).


1 Answers

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());
    });
});
like image 59
Nick Craver Avatar answered Sep 29 '22 11:09

Nick Craver