javascript - How to append unique spans to a table in jQuery? -


i have quick question, because brain refuses think evening.

html

<table> </table>  <span>2010</span> <span>2009</span> <span>2009</span> <span>2009</span> <span>2008</span> <span>2008</span> <span>2007</span> 

jquery

$('span').each(function() {         $("table").append("<tr><td>"+$(span).text()+"</span>)</td></tr>"; }); 

desired output

<table> <tr><td>2010</td></tr> <tr><td>2009</td></tr> <tr><td>2008</td></tr> <tr><td>2007</td></tr> 

the idea is, want display year not duplicated.

i hope understood me.

you can't inline string replacement that.

you need concatenate using javascript's (stupidly dual purpose) + operator.

you can't access span that. use this, jquery sets current element being iterated. wrap in $() use jquery on again.

to remove original, call remove() on $(this).

var yearsused = []; $('span').each(function() {     var text = $(this).text();         if ($.inarray(text, yearsused) === -1) {         $('table').append('<tr><td>' + text  + '</span>)</td></tr>');         yearsused.push(text);     }     $(this).remove(); }); 

you should pick 1 string delimiter , stick - here chose single quotes (').


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -