So basically my div generates like this:
content
content
<
ORIGINAL (See edit below)
As Jan Dvorak has asked, I'm not sure which properties you believe determine that an element is a duplication of another, however, the following is a not particularly quick but more generic solution to your problem:
(function($) {
$.fn.removeDuplicates = function() {
var original = [];
this.each(function() {
var el = this, $el, isDuplicate;
$.each(original, function() {
$el = $(el);
// check whichever properties
// you believe determine whether
// it's a duplicate or not
if (el.tagName === this.tagName &&
el.className === this.className &&
el.id === this.id &&
el.value === this.value &&
el.href === this.href &&
$el.html() === $(this).html()) {
isDuplicate = true;
$el.remove();
}
});
if (!isDuplicate) {
original.push(el);
}
});
};
}(jQuery));
You would use it like this:
$('.test').removeDuplicates();
// .. or even
$('div').removeDuplicates();
// .. or even
$('.test.className').removeDuplicates();
All of the above should work as expected, as demonstrated here.
EDIT
It's been a few years since I wrote this and I have since learnt of Node.isEqualNode. It gives a much cleaner way to do this so the updated plugin would look like the following (and would return the original element to chain against):
(function($) {
'use strict';
$.fn.removeDuplicates = function() {
var $original = $([]);
this.each(function(i, el) {
var $el = $(el),
isDuplicate;
$original.each(function(i, orig) {
if (el.isEqualNode(orig)) {
isDuplicate = true;
$el.remove();
}
});
if (!isDuplicate) {
$original = $original.add($el);
}
});
return $original;
};
}(jQuery));
A working example is demonstrated here.
something like this:
$('.className').not(':last').remove();
select all divs with .className
, remove the last one from the selection, remove the collection of divs, and you will just keep the last one.
demo: http://jsfiddle.net/j5728/
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.