JotaroUchiha
JotaroUchiha

Reputation: 25

Create Div and Append inside another div

I have a main container div, and a sidebar div. When clicking one of the sidebar divs, i want to create a div that is inside the container div. Here is what i have so far.

    <script>

$(function() {
$( "#container" ).sortable();
$( "#container" ).disableSelection();
});

function popUp(){
    var popup = document.createElement('div');
    popup.className = 'box3';

</script>

<ul id="container" style="position:relative;width:815;height:870;margin:20px;background-color:gray;">

    <li class="box2"></li>




</ul>
<div style="position:absolute;top:20;left:850;height:870px;width:320px;background-color:yellow;padding-left:15px;float:left;">
    <div id="add3" class="box3" style="height:15%;width:40%;" onclick="popup()" >Click Me to Add</div>
    <br/>
    <div id="add2" class="box2" style="height:15%;width:80%;">Click Me to Add</div>
</div>

Thoughts? Suggestions?

Upvotes: 0

Views: 1766

Answers (2)

ѺȐeallү
ѺȐeallү

Reputation: 3017

I want to move a nested DIV from sidebar into container using javascript.

Consider the following div structure:

<div id="sidebar">
   <div id="minidiv1">a</div>
   <div id="minidiv2">b</div>
</div>
<div id="container"></div>

To accomplish this I can simply append minidiv1 to the container, and it will change its location in the DOM:

$('#minidiv1').appendTo('#container'); 
// or
$('#container').append('#minidiv1');

The difference between the above two lines is what is returned, appendTo returns the #minidiv1 element, append will return the #container element.

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

Something simple like:

function popUp(){
    $('<div>').addClass('box3').appendTo('#container');
}

Where $('<div>') uses jQuery to create a new DIV element, which has a class added, then it is appended to the container*.

You should attached the click listener in code as well (get rid of the onClick=):

$('#add3').click(function(){
        $('<div>').addClass('box3').appendTo('#container');
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/K269E/3/

So your full code winds up something like:

$(function () {
    $("#container").sortable();
    $("#container").disableSelection();

    $('#add3').click(function () {
        $('<div>').addClass('box3').appendTo('#container');
    });
});

You have nothing in the new div of course, but you have not specified what you want to do next with it

Update to use an LI: http://jsfiddle.net/TrueBlueAussie/K269E/7/

$('<li>').addClass('box3').text("hello").appendTo('#container');

This one will add new LIs to your container UL (that simply says "hello" as an example).

Note:

You are wanting to inject a DIV into a UL (id=container), which is not valid HTML markup. You need to be a little clearer about the intended use.

Upvotes: 1

Related Questions