Undefined Variable
Undefined Variable

Reputation: 4267

Create div inside another dynamically

I am trying to dynamically create a div inside another using jquery, but it does not show up. My code is:

$(document).ready(function()
{
    $('#well_show').click(function(){
        $("#gen_div").empty(); //empty previous generated divs if any
        $("#gen_div").append("<div id='well'></div>"); //create new div
        $('#well').css("height","500px","width","500px","background-color","red"); 
    }); 
});

What am I doing wrong?

Upvotes: 0

Views: 928

Answers (3)

user3581054
user3581054

Reputation: 123

Use

.html("your html")

To fill it with your raw html

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78535

Your .css syntax is incorrect, you should pass in an object (see the docs for valid overloads). As it stands, you're accessing the css( propertyName, value ) overload and so only the height property is being applied.

$("#well").css({
    height: 500,
    width: 500,
    backgroundColor: "red"
});

I've cleaned up your code somewhat (replaced document.ready and chained the empty and append calls:

$(function() {
    $('#well_show').click(function(){
        $("#gen_div").empty().append("<div id='well'></div>"); //create new div
        $("#well").css({
            height: 500,
            width: 500,
            backgroundColor: "red"
        });
    }); 
});

jsFiddle Demo

Upvotes: 2

Tony Gustafsson
Tony Gustafsson

Reputation: 888

You don't append HTML, but a jQuery node. Like this:

$("#gen_div").append($("<div></div>").attr('id', 'well')); //create new div

Upvotes: 1

Related Questions