user1477388
user1477388

Reputation: 21440

Wrapping Generated Elements in jQuery

I am trying to create this:

<label><input id=""><span>Lorem ipsum dolor</span></label>

This is my code:

$('.property .includes')
    .append('<label>').html(
        $('<input>').attr('id', this.id) +
        $('<span>').html(this.description)
    );

It doesn't seem to work, as it just says, "[Object] [Object]."

How can I create the code above?

Upvotes: 1

Views: 64

Answers (4)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using like below,

$('.property .includes').append(
           $('<label />').append($('<input />', {'id': this.id}))
                         .append($('<span />').html(this.description))
     );

DEMO: http://jsfiddle.net/FJAjK/

Upvotes: 1

officert
officert

Reputation: 1232

mkoryak beat me to it.

    $('.property .include').append($('<label></label>')
                              .append($('<input></input>').attr('id', this.id))
                              .append($('<span></span>').html(this.description)));

Here's a JsFiddle for it too

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47119

You will have to change your code to:

$('<label/>')
    .append( $('<input>').attr('id', this.id) )
    .append( $('<span>').html(this.description) )
    .appendTo('.property .includes');

I'm also pretty sure you are trying to append the span and input elements to the label element.

I have chosen to use .appendTo as well instead of nesting function calls:

$('.property .includes').append(
  $('<label/>')
    .append( $('<input>').attr('id', this.id) )
    .append( $('<span>').html(this.description) )
);

Upvotes: 4

gustavohenke
gustavohenke

Reputation: 41440

You should be doing the following:

var label = $("<label />").html(
    "<input id='" + this.id + "'>" +
    "<span>" + this.description + "</span>"
);
$('.property .includes').append( label );

Upvotes: 1

Related Questions