Damir
Damir

Reputation: 56249

Create div and add style

I have one big div with id="elements" and I load from JSON file new elements objects and I need that for every element create new div inside elements ( elements div should contain lot off smaller divs, for every element one small div ). How to place this small divs inside this big div one behind another ? How to add this small divs a class style ?

Upvotes: 0

Views: 1035

Answers (4)

Stephen Chung
Stephen Chung

Reputation: 14605

In Dojo (since you have the dojo tag):

var div_elements = dojo.byId("elements");

dojo.forEach(json_data.items, function(item) {
    dojo.create("div", { "class":"whatever " + item.classNames }, div_elements);
});

Of course, you can put anything as the class for your div. I just provided an example. In the second argument to dojo.create, you pass in a hash containing all the properties you want that div to have.

Upvotes: 2

npellow
npellow

Reputation: 1985

Create a new DOM element like so:

var childDiv = document.createElement('div');

Then add to the outer div like so:

var insertedElement = div.insertBefore(childDiv, null);

You would then keep creating childDivs as you iterate over your JSON data, and inserting them into the div Node as above.

Upvotes: 2

Thorben
Thorben

Reputation: 6991

There a simple jQuery functions for that:

var box= $("#elements");
    // create elements
    for (var i=0; i<items.length; i++) {
        var t = $("<div class=\"element\" id=\"item_"+i+"\">"+items[i]['text']+"</div>");
        box.append(t);
    }

That's what you where looking for?

Upvotes: 1

Faraona
Faraona

Reputation: 1700

I think you need something like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></script>

<script type="text/javascript">

$(document).ready(function(){

json_data = 'Hey';

$('#elements').append('<div class="in_elements">' + json_data + '</div>');

});

</script>

<div id="elements">

</div>

Test it

Upvotes: 1

Related Questions