Alex Rivera | Logout

How do I create these nested dom elements with jquery?

Asked 2011-03-15T20:51:03.600
21

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?

Edit
Report

1 Answer

1
var div = $('<div>');
var div2 = $('<h1>');
var div3 = $('<a>');

div[0].id = "my_div";
div2[0].id = "my_header";
div3[0].class = "my_a_class";
div3.html("teststring");
$('#container').append(div.append(div2.append(div3)))
answered 2011-03-15T20:55:19.530

Your Answer