sqram
sqram

Reputation: 7201

Converting HTML string into jQuery set of elements

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.

Upvotes: 1

Views: 707

Answers (2)

SaidbakR
SaidbakR

Reputation: 13534

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

You have to use html method:

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

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

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();
    }

})

Upvotes: 6

Related Questions