Hobhouse Hobhouse - 4 months ago 7
Javascript Question

How do I create these nested dom elements with jquery?

Given these javascript variables:

var div_id = "my_div";
var h1_class = "my_header";
var a_class = "my_a_class";
var a_string = "teststring";


and this page element:

<div id="container"></div>


I want to build this html structure with jQuery:

<div id="container">
<div id="my_div">
<h1 class="my_header">
<a href="/test/" class="my_a_class">teststring</a>
</h1>
</div>
</div>


What is the best and most readable way to chain the commands here?

Answer

UPDATED

JSON

        var widgets = [{
            "div" : {
                "id" : "my-div-1"
            },
            "h1" : {
                "class" : "my-header"
            },
            "a" : {
                "class" : "my-a-class",
                "text" : "google",
                "href" : "http://www.google.com"
            }
        }, {
            "div" : {
                "id" : "my-div-2"
            },
            "h1" : {
                "class" : "my-header"
            },
            "a" : {
                "class" : "my-a-class",
                "text" : "yahoo",
                "href" : "http://www.yahoo.com"
            }
        }];

        $(function() {
            $.each(widgets, function(i, item) {
                $('<div>').attr('id', item.div.id).html(
                $('<h1>').attr('class', item.h1.class).html(
                $('<a>').attr({
                    'href' : item.a.href,
                    'class' : item.a.class
                }).text(item.a.text))).appendTo('#container');
            });
        });
Comments