I'm new to JS and jQuery. I wrote this function which just does what I want, but it seems very unreadable, and because of my experience, I don't know a better way to handle it.

Could you please give advise me how to refactor it?

function new_section(id, name, order) {

    return $('<tbody>')
        .attr('id', 'section_' + id)
        .attr('data-id', id)
        .attr('data-order', order)
            .attr('id', 'section_' + id + '_head_row')
                .attr('id', 'section_' + id + '_name_cell')
                .attr('colspan', window.row_length)

                .append($('<a>').addClass('edit-section').attr('href', '#')
                    .append($('<i>').addClass('fa fa-pencil text-muted')))

                .append($('<span>').addClass('pipe-edit-section text-muted').text('|'))

                .append($('<a>').addClass('section-up').attr('href', '#')
                    .append($('<i>').addClass('fa fa-chevron-up text-muted')))

                .append($('<a>').addClass('section-down').attr('href', '#')
                    .append($('<i>').addClass('fa fa-chevron-down text-muted')))

                .append($('<span>').addClass('pipe-edit-section text-muted').text('|'))

                 .append($('<a>').addClass('delete-section').attr('href', '#')
                    .append($('<i>').addClass('fa fa-times-circle text-muted')))



Found underscore templates. What do you think about this approach:

section = _.template([
            '<tbody id="section_<%= id %>" data-id="<%= id %>" data-order="<%= order %>">',
                '<tr id="section_<%= id %>_head_row" class="head-row">',
                    '<td id="section_<%= id %>_name_cell" class="bg-info" colspan="<%= row_length %>">',
                        '<%= name %>',
                        '<a href="#" class="edit-section">',
                            '<i class="fa fa-pencil text-muted"></i>',
                        '<span class="pipe-edit-section text-muted">|</span>',
                        '<a href="#" class="section-up">',
                            '<i class="fa fa-chevron-up text-muted"></i>',
                        '<a href="#" class="section-down">',
                            '<i class="fa fa-chevron-down text-muted"></i>',
                        '<span class="pipe-edit-section text-muted">|</span>',
                        '<a href="#" class="delete-section">',
                            '<i class="fa fa-times-circle text-muted"></i>',

1 Answer 1


There isn't much to refactor here and you already identified the problem scope.

You are much better off with a JavaScript template engine.

I won't be too opinionated here, but popular options are:


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.