Search code examples
javascriptjquerychildren

Check for duplicates when creating children for div


I would like to check that I am not creating a child with a duplicate title. However, I am not sure of the correct way to check and compare. Here's a code example of how the div's children are added:

this.foo = function(inputTitle)
{
    var title = inputTitle;

    var $ItemContainer = $("#ItemContainer");
    $ItemContainer.append('<div class="Item" title="'+title+'"></div>');

    // Continue to build the child
    var $thisItem = $ItemContainer.children('.Item[title='+title+']');
    $thisItem.append('<div class="ItemTitle">'+title+'</div>');
   // .....
}

The class will always be Item. How can I check that #ItemContainer does not already have a child with a duplicate title?


Solution

  • The following will tell you if there are any divs with a given title

    var exists = $('div[title="' + title + '"]').length > 0;