ambe5960
ambe5960

Reputation: 2000

append to element not in DOM tree

So I am building a div:

 var editArea =  '<div class="edit-container" style="padding-bottom: 10px;">' +
                '       <textarea class="form-control" style="margin-bottom:5px;">'+
                '       </textarea>' +
                '       <button type="button" class="btn right "><i class="fa fa-times-circle "></i>Leave Editor</button>'+
                '       <button type="button" class="btn submit-edit pull-right right " style="color:#fff;padding-top:5px; background-color: #3D8A11; border: 1px solid #f2f2f2;"><i class="fa fa-check-circle"></i>Submit</button>'+
                '</div>';

and want to append something to it before inserting it in the DOM:

for(i = 0; i < data.length; i++){
var fileLink = '<a href="#">' +data[i].username+'</a>';
editArea.('.edit-container').prepend(fileLink);
}

How would I go about doing this given my somewhat unconventional syntax for building the div? I am potentially open to building the initial div differently, if you suggest so. I just like that style for its one-line approach.

WHAT WORKED:

var editArea =  $('<div class="edit-container" style="padding-bottom: 10px;">' +
                    '       <textarea class="form-control" style="margin-bottom:5px;">'+
                    '       </textarea>' +
                    '       <button type="button" class="btn right "><i class="fa fa-times-circle "></i>Leave Editor</button>'+
                    '       <button type="button" class="btn submit-edit pull-right right " style="color:#fff;padding-top:5px; background-color: #3D8A11; border: 1px solid #f2f2f2;"><i class="fa fa-check-circle"></i>Submit</button>'+
                    '</div>');

Sincere thanks for the help. It is greatly appreciated.

Upvotes: 0

Views: 1315

Answers (1)

Dave
Dave

Reputation: 10924

jQuery can operate on items that detached from the DOM, so simply convert your text to a jQuery object and operate on that.

var $editArea = $(editArea); //converts text to a jQuery object
$editArea.prepend(fileLink);

If you need to get just the HTML string back:

$editArea.html()

Upvotes: 1

Related Questions