JonaNathali
JonaNathali

Reputation: 177

Creating nested DIVs on the fly using jQuery

I need to create several DIVs on the fly. The first DIV will be created on the <body> and next 3 DIVs will be inside the newly created DIV. Below is my approach in creating this. Please let me know if this is the best way to do it.

I want to create this HTML in jQuery.

<div id="aTextDV" class="ui-widget-content">
    <div class="txmoPos">
        <img src="img/markers/img1.png"/>
    </div>
    <div class="txdlPos" id="dleTx" onclick="dTxt('aTextDV')">
        <img src="img/markers/img3.png"/>
    </div>
    <div class="txrsPos">
        <img src="img/markers/img2.png"/>
    </div>
</div>

jQuery (I've created only 2 DIVs as for this example)

$(document).ready(function() {
    $('button').on("click", function() {
        $("body").append(
    $('<div/>')
      .attr("id", "aTextDV")
      .addClass("ui-widget-content")
    );
    $('#aTextDV').append(
    $('<div/>')
      .addClass("txmoPos")
      .attr("src", "img/markers/move.png")
    );
    })
})

Upvotes: 0

Views: 565

Answers (3)

Jackie
Jackie

Reputation: 96

$(document).ready(function() {
    $('button').on("click", function() {             
        $('body').append('<div id="aTextDV" class="ui-widget-content"></div>');
        $('#aTextDV').append('<div class="txmoPos"><img src="img/markers/move.png"/></div>');
        $('#aTextDV').append('<div class="txdlPos" id="dleTx" onclick="dTxt("aTextDV")"><img   src="img/markers/delete.png"/></div>');
        $('#aTextDV').append('<div class="txrsPos"><img src="img/markers/resize.png"/></div>');
    })
})

Upvotes: 1

r3wt
r3wt

Reputation: 4732

step 1: minify the html.

i use this site:

http://www.willpeavy.com/minifier/

step 2: make the minified html a javascript string, example:

 var $divdata = '<div class="foo"><p>some child content</p><div><div></div></div></div>';

step 3: append the div to the container

$('#aTextDV').append($divdata);

EDIT Always store backups of the normal (unminified)html. editing the minified html will be a pain in the butt later on. better to keep the unminified html for quick edits and repeat the process each time you need to edit.

Upvotes: 1

user2440074
user2440074

Reputation:

If the content you need is static - you can use jquery.load method - it's much more easier.

Upvotes: 0

Related Questions