7

What I'm trying to do is to create a table pager control using jQuery. It contains lots of links and spans. I've managed to do this with plain string concatenation, but I can't believe that jQuery can't make this more elegant. I can't use jTemplates here since the generation has quite a bit of procedural logic.

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

Thanks.

4 Answers 4

22

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

Sign up to request clarification or add additional context in comments.

2 Comments

This may have worked in 2009, but today it fails with an error message that depends on jQuery version. jsFiddle. What works is $('first').add($('second')).appendTo(...).
I tested this and @romkyns is right. I edited the answer accordingly.
11

String concatenation (or Array.join) is fine, as long as you make it pretty ;)

var structure = [
    '<div id="something">',
        '<span>Hello!</span>',
    '</div>'
];

$(structure.join('')).appendTo(container);

Comments

5

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 complex, and probably fastest option. However, following is an untested example of a way to (arguably) simplify the creation of elements, and allow you to append them to a given 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'));

Comments

0

You can just simplify things by doing like this :)

$('.parentElement').append(`
   <table style="width:100%">
     <tr>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Age</th>
    </tr>
    <tr>
      <td>Jill</td>
      <td>Smith</td>
      <td>50</td>
    </tr>
   </table>
`);

Just need to used `` or back quote inside the append method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.