javascriptjqueryhtmljquery-load

Append element from another page?


Given this HTML:

index.html:

<div class="tile" data-tilename="test">
    <div class="tileHeader">Tile Name</div>
</div>

tile-content.html:

<div id="test-tile" class="tileContent">
       <!-- lots of stuff here. -->
</div>

How can I arrive at the following?

<div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div class="tileContent">
       //lots of stuff here.
    </div>
</div>

Currently all these are created dynamically, so here is my current code:

let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
}).appendTo($elTile);

let $elTileContent = $('<div>').load('tile-content.html #' + tile.name + '-tile');
$elTile.append($elTileContent);

The last two lines above were inspired by this solution. Unfortunately it adds an extra <div> which I would like to avoid:

<div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div> <!-- I don't want this -->
        <div class="tileContent">
           <!-- lots of stuff here. -->
        </div>
    <div>
</div>

How can I arrive at the desired solution?


There are a couple similar questions, but none that I found have solutions and my situation is slightly different (dynamically created elements).


Solution

  • It's because you are creating that extra div by yourself here:

    let $elTileContent = $('<div>').load(...)
    

    You should load the content, then prepend the header:

    //create the tile and add it to the container
    let $elTile = $('<div/>', {
        class: 'tile'
    }).appendTo($elContainer);
    
    //create the header but do not add it yet
    let $elTileHeader = $('<div/>', {
        class: 'tileHeader',
        html: tile.header
    })
    
    //load the content into the tile
    $elTile.load('tile-content.html #' + tile.name + '-tile', function(){
        //on the "complete" callback, prepend the header
        $elTile.prepend($elTileHeader);
    });
    

    Happy Coding :)