var shiftid = []; var pre = "#"; $('table.shift').each(function(i){ shiftid[i] = $(this).attr("id"); } ); var element = pre + shiftid.join(', ' + pre); console.log(element);