Search code examples
jqueryvariablesappendchildren

JQuery: how to append one element of a variable inside an element of another variable?


I have used .load() to get two elements from a php file and have stored each in its respective variable:

var $one=("<div>");
$one.load("first-url form");  //the element is a form

var $two=("<div>");
$one.load("second-url #button"); //the element is a button with id #button

Using JQuery I would like to insert the #button of $two inside the <form> of $one.

Both consist of a <div> inside which reside the the actual elements.

I believe this could be attainable using a combination of .children() and .append() but I just can't figure it out.

Any help is appreciated.


Solution

  • While this would be possible with .load(), I feel that $.get() might be a bit easier.

    var content = $('#content');
    
    // Get the first file...
    $.get( "file1.html", function( data ) {
    
        // Append "file1.html" data to #content
        $(data).appendTo( content );
    
        // Get the second file...
        $.get( "file2.html", function( data ) {
    
            // Find #button element from "file2.html" 
            // data and append it to #content form.
            $(data).filter('#button').appendTo( content.find('form') );
    
        });
    
    });