Getting text from <li> and checking for duplicates and .append it ... by jQuery

HTML:

<li>Tue, 15th May 2012 10:11</li>
<li>Tue, 15th May 2012 10:12</li>
<li>Tue, 15th May 2012 10:13</li>
<li>Tue, 15th May 2012 10:14</li>
<li>Tue, 15th May 2012 10:15</li>
<li>Tue, 16th May 2012 21:08</li>
<li>Tue, 16th May 2012 21:07</li>
<li>Tue, 16th May 2012 21:06</li>
<code></code>

jQuery:

$("li").each(function () {
    words = $(this).text().split(' ');
    xxx = words[1]+" "+words[2]+" "+words[3]+",";
    $("code").append(xxx); 
});

I have come to this step now, but I do not know how to check the duplication date and add a unique date.

Demo: http://jsfiddle.net/4kvUy/

+5
source share
3 answers

Do this: -

if ($("code:contains('"+xxx+"')").length == 0)
   $("code").append(xxx);

EDIT:

To handle a comma, try as follows: -

if ($("code:contains('"+xxx+"')").length == 0){
    if ($("code").text() == '')
        $("code").append(xxx);
    else
        $("code").append(","+xxx);
}

EDIT2:

To handle this type of output, try this method: -

$("li").each(function () {
    words = $(this).text().split(' ');
    xxx = words[1]+" "+words[2]+" "+words[3];
    if ($("code:contains('"+xxx+"')").length == 0){     
        if ($("code").text() == '')         
            $("code").append('["'+xxx);     
        else         
            $("code").append('","'+xxx); 
    }
});
$("code").append('"]');

Conclusion:

["15th May 2012","16th May 2012"]
+2
source

One option is to use a :containsselector.

$("li").each(function() {
    words = $(this).text().split(' ');
    xxx = words[1] + " " + words[2] + " " + words[3] + ",";
    $("code:not(:contains(" + xxx + "))").append(xxx);
});​

DEMO: http://jsfiddle.net/4kvUy/2/

+2
source

Try this on jsfiddle , it works.

+1
source

All Articles