Is there a way to quickly build out a set of elements in jQuery? I know I can $('<div>').addClass('name'); a ton of times with .append() to create something like the example bellow but I was wondering if there is a better way to do it.
<div class="navBox">
<div class="topLeft"></div>
<div class="topRight"></div>
<div class="bottomLeft"></div>
<div class="bottomRight"></div>
<div class="hBar">
<div class="leftTab"></div>
<div class="rightTab"></div>
<div class="buttonLeft">
<div class="leftArrow"></div>
<div class="leftBar"></div>
</div>
<div class="buttonRight">
<div class="rightArrow"></div>
<div class="rightBar"></div>
</div>
</div>
<div class="vBar">
<div class="topTab"></div>
<div class="bottomTab"></div>
<div class="centerTab"></div>
<div class="buttonTop">
<div class="topBar"></div>
<div class="topArrow"></div>
</div>
<div class="buttonBottom">
<div class="bottomArrow"></div>
<div class="bottomBar"></div>
</div>
</div>
</div>
Update: I know I can brute force create it, I was hoping for something like jQuery building it for me based on a mark up like Zen-Coding or some such thing. I hoping to not have to include the block of HTML in code.
It depends if the content is going to be dynamic or not.
If static, just put the HTML in a single JS string and append using:
If you prefer to keep the HTML in your HTML file (makes sense), then you can make use of a
<script type="x-myTemplate">block:… and then retrieve the HTML using
$('#myTemplate').html(). Any content placed inside a<script>block with an unknowntypeattribute won’t be rendered by the browser.If dynamic, you can use the same method as above, but with jQuery’s templating engine.
You may also be interested in the lesser-known shorthand for creating elements in jQuery: