How to create multiple HTML elements using jQuery?

What I'm trying to do is create a table pager control using jQuery. It contains many links and intervals. I managed to do this with a simple string concatenation, but I can't believe jQuery can't make it more elegant. I cannot use jTemplates here because the generation has quite a bit of procedural logic.

Question: is there a way to create an array of HTML elements with jQuery and add them to some container?

Thanks.

+6
javascript jquery html
source share
3 answers

$(' First Element ').add($(' Second Element ')).appendTo($('body'))

+22
source share

The string concatenation (or Array.join) is fine if you do it pretty;)

 var structure = [ '<div id="something">', '<span>Hello!</span>', '</div>' ]; $(structure.join('')).appendTo(container); 
+8
source share

There is always append () .

 $('#container').append('<span>foobar baz</span>'); 

It seems to me that just using string concatenation and append would be the least complicated and probably the fastest option. However, the following unverified example of a method (possibly) simplifies the creation of elements and allows you to add them to this parent element:

 function elemCreate(type, content, attrs) { /* type: string tag name * content: string element content * attrs: associative array of attrs and values */ elem = '<' + type + '></' + type + '>' e = $(elem).attr(attrs) e.append(content) return e } stuff = []; stuff.push(elemCreate('a', 'Click me!', {'href': 'http://stackoverflow.com'}); $(stuff).appendTo($('#container')); 
+5
source share

All Articles