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());
});
});
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.
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.
Use . replace() method on HTML element and replace it with the new HTML Document(eg.. $('html'). html(Str)).
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());
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With