cmplieger
cmplieger

Reputation: 7351

edit ajax data before adding it to html

Hi is it possible to edit the contents of a GET ajax request before appending it to the content of the page?

I am getting the contents of the body of a new html page and would like to add some classes :).

This is probably impossible,

thank you for your help!

Upvotes: 0

Views: 85

Answers (3)

user415715
user415715

Reputation:

The way to do this without jquery is using document.createDocumentFragment

ajax({ //Your preferred method
    done: function(response){
        var myDom = document.createDocumentFragment();
        myDom.innerHTML = response.responseText;
        // your manipulations same as you would with "document"
        document.appendChild(myDom);
    }
});

Resources:

Upvotes: 0

J0HN
J0HN

Reputation: 26921

If you are using jQuery, you could try the following (note that it could be extremely resource-consuming, depending on your loaded page size):

$.ajax({
    /*parameters here*/
    success: function(data,textStatus){
        processData(data);
    }
});

function processData(data){
    //this line creates jQuery object that contains DOM model for loaded page
    var page = jQuery(data); 

    page.find('#id-of-element-to-add-some-class').addClass('*your class*');
    page.find('#table').addClass('myTable'); //adds class myTable to all tables in the document
    //placeholder for loaded page content. Could be something like $('#placeholder')
    var target_element = document; 

    $(target_element ).append(page);
}

See jQuery.ajax for details

Upvotes: 0

Keith Rousseau
Keith Rousseau

Reputation: 4475

It's definitely not impossible. You just need a way to parse it. The easiest way to do it would actually be to append it to your page in a hidden container and then do any DOM manipulations you need. Then you can just relocate the html or show it if it's in the right place.

If you are using jQuery, you can actually perform any of the jQuery operations on the html string that you get back. However, this is quite a bit less performant in certain older browsers.

Upvotes: 1

Related Questions