Prevent appending duplicated content in jQuery

html, javascript, jquery

Solution

You can use the `:contains()` selector to find a DIV with the same text as the current `DIV` in the loop.

$('.addall').click(function(){
    var add = $(this).closest('.addarea').find('.add');
    add.each(function(){
        var content = $(this).text();
        if ($('#area > div:contains('+content+')').length == 0) {
            $('#area').append($(this).clone());
        }
    });
});

DEMO

Note that this only works in your application because the DIVs just contain a single letter. `:contains(X)` looks for a DIV where `X` is any substring, not the entire contents.

You shouldn't use `return false` when finding a match, as that will terminate the loop, not just the current iteration.

Problem

Please take a look at this fiddle. I have been working on "Add All" buttons that append text to `div#area`. Can anyone tell me how to use an if condition to prevent duplicated text from adding to the area? In the fiddle example, I don't want "A","B" to be appended twice to the area. HTML: ``` <div class="addarea"> <div class="add">A</div> <div class="add">B</div> <div class="add">C</div> <div class="add">D</div> <button class="addall">Add All</button> </div> <div class="addarea"> <div class="add">A</div> <div class="add">B</div> <div class="add">F</div> <div class="add">G</div> <button class="addall">Add All</button> </div> <button id="remove">Remove</button> <div id="area"></div> ``` Failed Code: ``` $('.addall').click(function(){ var add = $(this).closest('.addarea').find('.add'); add.each(function(){ var copy = $(this).clone(), content = $(this).text(); if($('#area').find('.add').text() == content){ return false; } else { $('#area').append(copy); } }); }); $('#remove').click(function(){ $('#area').find('div').remove(); }); ```

Original source