Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create nested HTML elements with jQuery [closed]

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.

like image 293
Maverick Avatar asked Jun 23 '12 22:06

Maverick


People also ask

What is the most efficient way to create HTML elements using jQuery?

Conclusion: The $(document. createElement('div')); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery.

Is it good practice to limit nesting of HTML elements?

Actually there is no limit for tag nesting levels, it is just a matter of good practices. Maintaining a code with many levels may find a hard thing to keep doing along the time.

Can HTML elements be nested?

HTML elements can be nested (this means that elements can contain other elements). All HTML documents consist of nested HTML elements.


2 Answers

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.

like image 71
lucideer Avatar answered Sep 19 '22 11:09

lucideer


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 ); 
like image 23
Hugh Chapman Avatar answered Sep 21 '22 11:09

Hugh Chapman