开发者

How to find and replace a div in a text response from AJAX

How would I be able to find and replace a div (or other tag) in HTML which is saved as text开发者_如何学C 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.

$.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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜