Search code examples
javascriptjqueryjqxhr

How do I filter body html the returned data from ajax?


My purpose is, I want to take specific html out from data and update that area only.

How do I filter the returned data from jQuery.ajax?

This link is a old post but I do have the exactly same problem.

The solution giving from the link is $("[ref=B]").html(data).find( '[ref=A]' );

However, if I do so, the entire page will write on <span ref='B'> first then find the selector inside of it.....

The alternative way to only find '[ref=A]' is

html = $(data).filter('[ref=B]').find('[ref=A]').html() // this way will work

none of these will work

$(data).find('[ref=A]').html();
$(data).filter('[ref=A]').html();
$(data).filter('body').html();
$(data).find('body').html();

HTML

`<body>

<span ref='B'><span ref='A'>abc</span></span>

</body>`

JS

 $(function() {
$.get(window.location.pathname + window.location.search, function(data){ alert(data);});
 });

Returned Data

<html>
<body>
    <span ref='B'><span ref='A'>abc</span></span>
</body>
</html>

My question is, is there a solution to filter body`s html from data which returned from $.ajax?? like

body_html = $(data).??????? 

then I can do whatever I want, like

body_html.find('xxxx');

Thank you very much for your advice.


Solution

  • You can use a DocumentFragment to simulate your html and do your search without appending it to the DOM.

    // Create your DocumentFragment to be able to work without DOM
    var body_html = document.createDocumentFragment();
    
    // Convert and append data from your jQuery to work with fragment
    body_html.appendChild($(data)[0]);
    
    // Now you can select using your jQuery
    var $body_html = $(body_html);
    
    // Now you can use the find or whatever you want, like if it was in the DOM
    $body_html.find('.foo');
    
    // Or you can append in your current document, 
    // but attention, after it the fragment reference is erased
    $body_html.appendTo(document.body); 
    // now you need to get reference again from body, 
    // because your fragment doesn't exists anymore.
    
    // So... if you try:
    console.log(body_html); // undefined
    console.log($body_html); // jquery over undefined, probably just a jquery useless
    
    // At this point you will need to reference from DOM to continue manipulation
    $body_html = $(document.body);
    // Now I'm ready to continue the work
    // This var is like your DocumentFragment, but already on DOM.
    

    You also can do a filter in jQuery templating $(data).filter('.foo') but as you can see in this tests, your performance will drop a lot.