Sora
Sora

Reputation: 2551

Remove all div with same html value using jQuery

I have the following html structure

 <div class="messagesdate">03 Aug, 2021</div>
  <div class="messagesdate">03 Aug, 2021</div>
  <div class="messagesdate">03 Aug, 2021</div>
  <div class="messagesdate">04 Aug, 2021</div>
  <div class="messagesdate">04 Aug, 2021</div>

How can I do a global function that will run through all the div and remove all with same date except for the first one?

this is what I did so far and I got stuck

var found = {};
        $('.messagesdate').each(function (i) {
            var $this = $(this);
            if (found[$this.html()]) {
                $this.remove();
            } else {
                found[$this.html()] = true;
            }
        });

Upvotes: 0

Views: 57

Answers (2)

SameerUllah
SameerUllah

Reputation: 209

$('.messagesdate').each(function (i) {

         if(i == 0)
           var firstElement = $(this);
         else{
              if($(this).html() == firstElement.html()){
              $(this).remove()
           }
     }    

});

Upvotes: 0

KooiInc
KooiInc

Reputation: 122906

Can be done without jQuery

const dates = {};
document.querySelectorAll("div.messagesdate")
  .forEach(div =>
    dates[div.textContent] ? div.remove() : dates[div.textContent] = 1);
<div class="messagesdate">03 Aug, 2021</div>
<div class="messagesdate">03 Aug, 2021</div>
<div class="messagesdate">03 Aug, 2021</div>
<div class="messagesdate">04 Aug, 2021</div>
<div class="messagesdate">04 Aug, 2021</div>

Upvotes: 1

Related Questions