THX-1138
THX-1138

Reputation: 21730

jQuery: set a jQuery object as a [html] content

Is there a shortcut for:

var child = $('<span>error message</span>');
$('#parent').html(child.html());

or, the same

var child = $('<span>error message</span>');
$('#parent').empty().append(child);

EDIT: above example won't work if I try to assign same child to multiple parents, my child object can only belong to a single parent (which is not what I wanted in my case).

I do realize I could do:

$('#parent').html('<span>error message</span>');

but I want to reuse child object.
EDIT: again, this won't work, since child is a DOM object and can only be placed under at most one parent at any time.

I am looking for something like:

var child = $('<span>error message</span>');
$('#parent').content(child);

Upvotes: 0

Views: 161

Answers (4)

THX-1138
THX-1138

Reputation: 21730

var child = $('<span>error message</span>').attr({ 'class' : 'error-message'});
$('#parent').html(child.clone()); 

notice that you have to clone() child unless you want to actually move child from its previous parent.

credits to both Tules and Felix Kling

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

You can always wrap functionality in a plugin:

(function($) {
    $.fn.setContent = function(content) {
        return this.empty().append(content);
    };
}(jQuery));

$('#parent').setContent(child);

Also if you want to reuse an existing jQuery object, you probably have to use .clone() if you want to insert it later somewhere else.

Upvotes: 2

Richard Banks
Richard Banks

Reputation: 2983

you could try something like

      var child = $('#parent').html('<span>error message</span>').children('span:eq(0)');

Ive not tried it myself. To be honest your first example seems pretty good to me.

Upvotes: -1

Tules
Tules

Reputation: 4915

var child = '<span>error message</span>';
$('#parent').html(child);

is the shortest you are possibly gonna get, how short does it really need to be? lol

Upvotes: 1

Related Questions