-1

i have this script to remove duplicate elements by class using jquery, is there a way to do it with pure javascript? this is my code

  <script >$(document).ready(function() {
    var seen2 = {};
    $('.listofarticlescolor').each(function() {
        var txt2 = $(this).text();
        if (seen2[txt2])
          $(this).closest('.category').remove();
        else
            seen2[txt2] = true;
    });

    });
</script>
  • 1
    What kind of help do you need? We're not going to write it for you, that's your job. Show what you tried, and we'll help you understand where you went wrong and how to fix it. – Barmar Apr 25 '16 at 19:39
  • hello thanks for the reply,im just stuck in how to use closest in pure javascript – Mounir Federere Apr 25 '16 at 20:06
  • you don't, because it doesn't exist. You would have to crawl up the tree until you found your element instead. it would probably be easier to loop over the .category elements and work downward. – Kevin B Apr 25 '16 at 20:33

1 Answers1

0

Try this code, to make it work first you have to convert the list of nodes in an array, then do something similar to what you've done.

var classWillRemove = [].slice.call(document.getElementsByClassName('listofarticlescolor'));
var seen2 = {};
for(i=0;i< classWillRemove.length;i++){
     var text = classWillRemove[i].innerHTML;
     if (seen2[text]){
         classWillRemove[i].parentNode.removeChild(classWillRemove[i]);
    } else {
         seen2[text] = true;
    }
}

Demo :http://jsfiddle.net/6h7rxqr1/

NopalByte
  • 159
  • 5
  • the problem im stuck in,is how to remove parent class with pure javascript...llike how to use closest in javascript? – Mounir Federere Apr 25 '16 at 20:42
  • The key is the closest jquery function, replace it with one that does the same, you can see this response so you can see as implemented. [closest in pure javascript](http://stackoverflow.com/a/22101242/6237596) – NopalByte Apr 25 '16 at 20:49
  • i been struggling with this for hours cant find how to make it work i made http://jsfiddle.net/L0xpva19/ can you help me make it work plz – Mounir Federere Apr 25 '16 at 22:11
  • hey bro, there is a problem with your script,if i add more divs with same content the script doesnt work take a look http://jsfiddle.net/0wbogwzc/ – Mounir Federere Apr 26 '16 at 08:38
  • I fixed, first you have to convert the list of nodes in an array, i updated the answer. – NopalByte Apr 26 '16 at 14:33
  • thank you so much for your patient and help with me :) i apreciate it. – Mounir Federere Apr 27 '16 at 18:42