1

I currently use $.get() to fetch HTML markup from another file. How can I add the results to the current jQuery set of matched elements for the current DOM?

I thought add() would do the trick, but it doesn't. For instance, this doesn't work:

$.get('file.html', function(data) {
    $('body').add(data)
});

But ideally, if file.html has, say, '', i'd like to be able to use #result like it was in the current set of elements, with $('#result').html(..).

One thing I could do, is use $.load('file.html #result')... but i'd have to do this multiple times as i'll be working with multiple elements.

My thought then was perhaps to use

sub$ = jQuery.sub();

and add the returned string of HTML from $.get to it, but don't know if it's possible.

2
  • 1
    Do you want to append() the data to body element or update the elements based on the response? Commented Dec 9, 2012 at 15:46
  • Update I guess. For instance, one of the elements I get is a button. I would want to add that button inside a certain div in the current DOM. Commented Dec 9, 2012 at 15:53

2 Answers 2

6

You can turn the whole html response into a jQuery object without inserting it into the DOM. This allows you to manipulate or look for specific elements or values and do different things with different parts of the response.

Example:

$.get('file.html', function(data) {
    var $response=$(data);
    var myButton=$response.find('button');

     var someDiv= $response.find('#someDiv').css('color','red')
     $('#someForm').append( myButton)

     $('body').append( someDiv)
});

You can also check for certain elements existence, or certain values within the response and process the response accordingly.

$.get('file.html', function(data) {
   var $response=$(data);

    if( $response.find('#someDiv').length){
      doThis();
    }else{
       doThat();
    }

})
Sign up to request clarification or add additional context in comments.

1 Comment

some use $ when creating a jQuery object as a convention to know that is is a jQuery object and not a value, array or object literal
0

Simply look at jQuery documentation http://api.jquery.com/html/

You have to use html method:

$.get('file.html', function(data) {
    $('body').html(data);
});

2 Comments

This isn't what I want. This will replace the entire content of the body.
so it is easy, instead of body use another selector such as an div with id #someId!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.