views:

41

answers:

4

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
    }
});
+3  A: 

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.

$.ajax({
    url: 'page.pgp',
    success: function(result) {
        var $result = $(result);
        $result.find( 'div' ).replaceWith('<span>something else</span>');
        $result.appendTo('body');
    }
});

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.

patrick dw
A: 

Can you elaborate your problem please .............

Umakanta.Swain
Your answer should actually be a comment
MikeG
This would've been better to have as a comment on the original question as it's not a reply.
XIII
@Mike: true, but that requires 50 rep.
Matt Ball
@Bears: Ah yes, thanks.
MikeG
A: 

Wrap the response in jQuery and traverse it like always:

$.ajax({
    url: 'page.pgp',
    success: function(result) {
        result = $(result).find('.your-selector').replaceWith('<div></div>').end().html();
    }
});

Note that you do not need to use .html() afterwards.

elusive
Just FYI, `result` will contain the HTML content of the `.your-selector` you were replacing because `replaceWith()` returns the one that was replaced. :o)
patrick dw
@patrick dw: Oops, i corrected that.
elusive
A: 

If your response is returning a valid HTML structure then you should be able to throw it into the jQuery factory function $(result).

$(result).find('div') // do something
John Strickler