Joseph
Joseph

Reputation: 113

JQuery append element to div

I'm doing some code where i need to append labels to a div and then append the same to the body.

I run the program and i saw that the div is created but the labels cannot be attached to the div:

Here is my code

var divName = "div-isoparameters";

function createComponents() {
    createDiv();
    createLabels(divName);
}

function createDiv() {
    var $div = $('<div />').appendTo('body');
    $div.attr('id', divName);
    $div.attr('class', divName);
    $div.css("display","block");
}

function createLabels(divName) {
    for (var i = 0; i < 10; i++) {
        var $label = $("<label>").text( "label something: ");
        //Create the input element
        var $input = $('<input type="text">').attr({ id: 'something', name: 'something' });

        //Insert the input into the label
        $input.appendTo($label);

       $(divName.id).append($label);
    }
}

I dont know what i'm doing wrong since i'm appending the div to the body and then i append all the labels to the div

Upvotes: 0

Views: 1004

Answers (2)

Andrew Shepherd
Andrew Shepherd

Reputation: 45222

Your problem is in the last line of code:

        $(divName.id).append($label);

That's not how you select items by id. If you know the item ID, you select it in jQuery by prepending a # character to the id.

For example, if the div had an id of labelHolder:

 $('#labelHolder').append($label);

So you have two choices:

Either manually prepend the crosshatch:

$('#' + divName).append($label);

Alternatively, you can retrieve the element through a call to document.getElementById(...). This is my preferred choice, because it's clearer what you're doing.

$(document.getElementById(divName)).append($label);

Upvotes: 1

lxcky
lxcky

Reputation: 1668

$("#"+divName).append($label); 

You forgot to add # on the div name. Also I removed the .id because you're already passing the ID name which is div-isoparameters. Basically you're getting the DOM $("#div-isoparameters").

Upvotes: 0

Related Questions