Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove duplicated div with class name

Tags:

jquery

So basically my div generates like this:

<div class="test className">content</div>
<div class="test className">content</div>
<div class="test className">content</div>
..
<div class="test className">content</div>

and I'm trying to remove duplicated divs and keep last one only! any quick ideas? thanks!

like image 393
test Avatar asked Dec 09 '12 19:12

test


1 Answers

A quick idea based on your provided markup.

var $div = $('div.test.className:contains(content)');

if ($div.length > 1) {
   $div.not(':last').remove()
}

But I would prevent duplication at first place.

edit: Here is another alternative using filter and slice method:

$('.test.className').filter(function() {
    return this.textContent === 'content';
}).slice(0, -1).remove();

In the above snippet by using -1 as the second argument of the .slice method, the last element in the set is ignored.

like image 111
undefined Avatar answered Sep 21 '22 04:09

undefined