RedGiant
RedGiant

Reputation: 4748

Prevent appending duplicated content in jQuery

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();
});

Upvotes: 3

Views: 6546

Answers (3)

Bewusstsein
Bewusstsein

Reputation: 1621

Description for .text() from the jQuery-API:

Get the combined text contents of each element in the set of matched elements

Thus this $('#area').find('.add').text() returns the concatenated content of all .add-elements in #area ('A B C D' or 'A B F G' in your example).

You'll have to check the content of each element separately, or via jQuery-selector: $('#area').find(".add:contains('" + content + "')").length > 0

Upvotes: 1

Barmar
Barmar

Reputation: 780818

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.

Upvotes: 8

John C
John C

Reputation: 666

I would use an array to store the content values, then check those values.

var textArray = [];
...
if ($.inArray(content,textArray) === -1) {
...

DEMO

Upvotes: 1

Related Questions