Jamie Taylor
Jamie Taylor

Reputation: 3530

hide duplicate div in jquery

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

Upvotes: 1

Views: 2605

Answers (5)

amof
amof

Reputation: 416

This works:

var a = new Array();

$('p').each(function(index) {
    text = $(this).text();
    if($.inArray(text, a)!=-1){
        $(this).closest('p').hide();
    }else{
        a.push(text);
    }
});

http://jsfiddle.net/WjgxQ/59/

Upvotes: 0

sled
sled

Reputation: 14625

Have a look at:

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

This does exactly what you're looking for ;)

Upvotes: 1

karim79
karim79

Reputation: 342635

// 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/

Upvotes: 1

simplyharsh
simplyharsh

Reputation: 36373

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);
    }
});

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382666

Try this:

var arr = new array();

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

Upvotes: 0

Related Questions