I asked you for some markup where there are duplicates to look for a "patern" to exploit.
And you provided some markup that really doesn't look like a real use-case markup. Example: A <video>
usually has some <source>
tags inside and a closing tag... And </img>
is invalid. I was tempted not to answer at all... Because of this lack of serious.
But I then had an idea of something to do that might work after all...
So here is a code that works for the provided sample... It may work fine on your real markup and it may have plenty issues.
It's a starter without any waranty. You will have to improve it yourself from here. Look below for the explanations on how it works.
$(".clean").on("click",function(){
var all_elements = $(".parent").children();
all_elements.each(function(){
var el_class = this.className;
var el_src = this.src;
var el_text = $(this).text();
// data("verified") prevents the removal triggered by it's duplicate, if any.
$(this).data("verified",true);
all_elements.each(function(){
if(el_class==this.className && el_src==this.src && el_text==$(this).text() && !$(this).data("verified")){
$(this).remove();
}
});
});
// Turn all "surviving" element's data("verified") to false for future "clean".
$(".parent").children().each(function(){
$(this).data("verified",false);
});
});
.parent>*{
border:1px solid black; /* Just to make empty element more obvious in this demo */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn clean">CLEAN DUPLICATES</button><br>
<br>
<div class="parent">
<div class="child">hello</div>
<div class="child">hello</div>
<img class="flower_image" src="/pictures/flower.jpeg">
<img class="flower_image" src="/pictures/flower.jpeg">
<video class="trailer_video" src="/videos/trailer.flv"></video>
<video class="trailer_video" src="/videos/trailer.flv"></video>
<span class="span_text">hello world></span>
<span class="span_text">hello world></span>
<a class="hyper_link" src="www.example.com"></a>
<a class="hyper_link" src="www.example.com"></a>
</div>
There are two nested .each()
loops working on all the elements that are child of .parent
.
It compares two attributes:
- the
className
(class list of the element)
- the
src
and the text it contains.
If something is empty or undefined, it doesn't matter because the duplicate it looks for should also be empty or undefined.
And finally, there is a data
value used as a flag to prevent an element, which was the subject of a previous comparison, to be removed.