views:

38

answers:

2

I have a quick question, because my brain refuses to think this 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, that I want to display just a year that is not duplicated.

I hope that you understood me.

A: 
$('span').each(function() {
  $("table").append("<tr><td>" + $(this).text() + "</td></tr>");
  $(this).hide();
  });
Amber
Also correct, but a quick note on the difference between this code and alex's: $.hide only sets the element's display property to "none", while $.remove removes the element from the DOM completely. Which one you should choose depends on whether you want to do any future processing on those spans.
C-Mo
+2  A: 

You can't do inline string replacement like that.

You need to concatenate using JavaScript's (stupidly dual purpose) + operator.

You also can't access the span like that. Use this, which jQuery sets as the current element being iterated. Wrap it in $() to use jQuery on it again.

To remove the original, just 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 also pick one string delimiter and stick with it - here I chose single quotes (').

alex
lol, I just change this line "if ($.inArray(text, yearsUsed) === -1" as well
Alexander Corotchi
Anyways, it is amazing, so great idea. Thanks man so much !!!!!!
Alexander Corotchi