Best way to create nested HTML elements with jQuery

JavascriptJqueryDomNested

Javascript Problem Overview


If I need to create a couple of nested DOM elements, I know one way to do it, is to write them as long string and then place them in the document using a suitable jQuery function. Something like:

elem.html(
'<div class="wrapper">
    <div class="inner">
        <span>Some text<span>
    </div>
    <div class="inner">
        <span>Other text<span>
    </div>
</div>'); 

This way is obviously not the cleanest. The sting doesn't take too long to get messy and editing becomes a problem. I much more prefer this notation:

$('<div></div>', {
    class : 'inner'
})
.appendTo( elem );

The problem is I don't know how to implement it efficiently when creating nested elements on the fly like above. So if there is way to do the 1st example with the 2nd notation, I'll be glad to learn about it.

Basically, the question is, whats the best way to create nested HTML elements on the fly, without having to deal wit messy long strings?

Note : I am aware of templating engines. However this is a question concerning the creation of just a couple of HTML elements on the fly. Like while building the DOM dependencies for a plugin or similar cases.

Javascript Solutions


Solution 1 - Javascript

> write them as long string and than place them in the document using a > suitable jQuery function. Something like:

The problem with this approach is that you'll need a multi-line string - something Javascript doesn't support - so in reality you'll end up with:

elem.html(
'<div class="wrapper">'+
	'<div class="inner">'+
		'<span>Some text<span>'+
	'</div>'+
	'<div class="inner">'+
		'<span>Other text<span>'+
	'</div>'+
'</div>');

Using the method you suggested above, this is about as clean as I could manage to get it:

elem.append(
	$('<div/>', {'class': 'wrapper'}).append(
		$('<div/>', {'class': 'inner'}).append(
			$('<span/>', {text: 'Some text'})
		)
	)
	.append(
		$('<div/>', {'class': 'inner'}).append(
			$('<span/>', {text: 'Other text'})
		)
	)
);

The other advantage to doing this is that you can (if desired) get direct references to each newly created element without having to re-query the DOM.

I like to write polyglots, so to make my code re-usuable I usually do something like this, (as jQuery's .html() doesn't support XML):

// Define shorthand utility method
$.extend({
	el: function(el, props) {
		var $el = $(document.createElement(el));
		$el.attr(props);
		return $el;
	}
});

elem.append(
	$.el('div', {'class': 'wrapper'}).append(
		$.el('div', {'class': 'inner'}).append(
			$.el('span').text('Some text')
		)
	)
	.append(
		$.el('div', {'class': 'inner'}).append(
			$.el('span').text('Other text')
		)
	)
);

This isn't very different to method #2 but it gives you more portable code and doesn't rely internally on innerHTML.

Solution 2 - Javascript

I found this solution while I was researching something else. It's part of an "Introduction to jQuery" by the creator of jQuery and uses the end() function.

$("<li><a></a></li>") // li 
  .find("a") // a 
  .attr("href", "http://ejohn.org/") // a 
  .html("John Resig") // a 
  .end() // li 
  .appendTo("ul");

Applying to your question it would be ...

$("<div><span></span></div>") // div 
  .addClass("inner") // div 
  .find("span") // span 
  .html("whatever you want here.") // span 
  .end() // div 
  .appendTo( elem ); 

Solution 3 - Javascript

I like the following approach myself:

$('<div>',{
  'class' : 'wrapper',
  'html': $('<div>',{
    'class' : 'inner',
    'html' : $('<span>').text('Some text')
  }).add($('<div>',{
    'class' : 'inner',
    'html' : $('<span>').text('Other text')
  }))
}).appendTo('body');

Alternatively, create your wrapper first, and keep adding to it:

var $wrapper = $('<div>',{
    'class':'wrapper'
}).appendTo('body');
$('<div>',{
    'class':'inner',
    'html':$('<span>').text('Some text')
}).appendTo($wrapper);
$('<div>',{
    'class':'inner',
    'html':$('<span>').text('Other text')
}).appendTo($wrapper);

Solution 4 - Javascript

There is a third way besides long ugly strings or huge methods chained together. You can use plain old variables to hold the individual elements:

var $wrapper = $("<div/>", { class: "wrapper" }),
    $inner = $("<p/>", { class: "inner" }),
    $text = $("<span/>", { class: "text", text: "Some text" });

Then, tie it all together with append:

$wrapper.append($inner.append($text)).appendTo("#whatever");

Result:

<div class="wrapper">
  <p class="inner">
    <span class="text">Some text</span>
  </p>
</div>

In my opinion this is by far the cleanest and most readable approach, and it also has the advantage of separating the data from the code.

EDIT: One caveat, however, is that there is no easy way to mix textContent with nested elements (e.g., <p>Hello, <b>world!</b></p>.) In that case you would probably need to use one of the other techniques such as a string literal.

Solution 5 - Javascript

I like this approach

	$("<div>", {class: "wrapper"}).append(
	    $("<div>", {class: "inner"}).append(
	        $("<span>").text(
	            "Some text"
	        )
	    ), 
	    $("<div>", {class: "inner"}).append(
	        $("<span>").text(
	            "Some text"
	        )
	    )
	).appendTo("body")

Solution 6 - Javascript

Long string is obviously the cleanest way possible. You see the code properly nested without all those unnecessary extra noise like brackets, dollar signs and what not. Sure, it'd be advantages to be able to write it as a multiline string, but that's not possible for now. To me the point is to get rid of all the unneeded symbols. I don't know how comes the string gets messy and editing becomes a problem. If you've assigned a lot of classes you can put them on separate line:

'<div id="id-1"'
+ ' class="class-1 class-2 class-3 class-4 class-5 class-6">'
+ '</div>'

or this way:

'<div id="id-1" class="'
    + 'class-1 class-2 class-3 class-4 class-5 class-6'
+ '">'
+ '</div>'

Another option is probably to use haml on the client side, if that's possible. That way you'll have even less unneeded noise.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaverickView Question on Stackoverflow
Solution 1 - JavascriptlucideerView Answer on Stackoverflow
Solution 2 - JavascriptHugh ChapmanView Answer on Stackoverflow
Solution 3 - JavascriptBrad ChristieView Answer on Stackoverflow
Solution 4 - JavascriptjackvsworldView Answer on Stackoverflow
Solution 5 - Javascriptmatt3141View Answer on Stackoverflow
Solution 6 - Javascriptx-yuriView Answer on Stackoverflow