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)
.append($('<tr>')
.addClass('head-row')
.attr('id', 'section_' + id + '_head_row')
.append($('<td>')
.attr('id', 'section_' + id + '_name_cell')
.attr('colspan', window.row_length)
.text(name)
.addClass('bg-info')
.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')))
)
);
}
UPD:
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>',
'</a>',
'<span class="pipe-edit-section text-muted">|</span>',
'<a href="#" class="section-up">',
'<i class="fa fa-chevron-up text-muted"></i>',
'</a>',
'<a href="#" class="section-down">',
'<i class="fa fa-chevron-down text-muted"></i>',
'</a>',
'<span class="pipe-edit-section text-muted">|</span>',
'<a href="#" class="delete-section">',
'<i class="fa fa-times-circle text-muted"></i>',
'</a>',
'</td>',
'</tbody>'].join('\n'));