How would I be able to find and replace a div (or other tag) in HTML which is saved as text in a variable? I get the HTML as a text response from ajax:
$.ajax({
url: 'page.pgp',
success: function(result) {
// here I want to find certain HTML tag
// in result variable and replace it with something else
}
});
You can turn your HTML response into DOM elements stored in a jQuery object by wrapping it with
$(). Then just use.find()to locate what you’re looking for, and use.replaceWith()to remove it and replace with new content.This example will replace all
<div>elements found. You may need to make the selector more specific.Note that if the
<div>you’re looking for is at the top level of the elements, you’ll need to use.filter()instead.The example the uses
.appendTo()to insert the result.