views:

48

answers:

4

I have some layers that are dynamically put in as follows

<div><p class="locid">2<p></div>
<div><p class="locid">1<p></div>
<div><p class="locid">2<p></div>
<div><p class="locid">3<p></div>
<div><p class="locid">4<p></div>

What I need to do is hide the second occurrence of this layer so it appears as follows

<div><p class="locid">2<p></div>
<div><p class="locid">1<p></div>
<div><p class="locid">3<p></div>
<div><p class="locid">4<p></div>

Any ideas?

Thanks

Jamie

+1  A: 
// get a collection of p's matching some value
$("p.locid").filter(function() {
    return $(this).text() == '2';

// hide the (div) parent of the second match
}).eq(1).parent().hide();

Demo: http://jsfiddle.net/WjgxQ/

karim79
This one only works if the content is literally "2". I don't think it's what the question is about.
Litso
My understanding is along the lines of: 'given some value, I want to hide the div which matches the second occurrence of that value'.
karim79
Same. In that case I don't understand your script :P
Litso
@Litso - I've thrown in comments, in case it helps.
karim79
This works if I only have one duplicate on the page but if I have more than one duplicate it only hides the first duplicate.
Jamie Taylor
My fault it works many thanks
Jamie Taylor
A: 

Try this:

var arr = new array();

$('.locid').each(function(){
  if ($.inArray($(this).text(), arr) !== -1){
     $(this).closest('div').remove();
  }
  else{
    arr[] = $(this).text();
  }
});
Sarfraz
+1  A: 

Hi,

have a look at:

http://api.jquery.com/jQuery.unique/

This does exactly what you're looking for ;)

Greets

Simon

sled
That's not actually what `jQuery.unique()` does. It only removes duplicates if they are the same actual element. So if you have two elements that have the same content, class, etc., so they appear to be identical, they are actually considered to be two unique elements because they are not the same element. They just look the same. As such, `jQuery.unique()` would not remove either one. :o)
patrick dw
whoops... you're right.. won't work in this case.
sled
+1  A: 

Interesting. Try this.

var a = new Array();
$('p.locid').each(function(){
    text = $(this).text();
    if($.inArray(text, a)){
        $(this).closest('div').hide();
    }else{
        a.push(text);
    }
});
simplyharsh