Alan2
Alan2

Reputation: 24572

How can I detect if a jQuery .append has already been applied

I have code that appends as follows:

if (json.expData[i] != null) {
    $('#text' + i)
    .append("<br><br><img src='/balloon.png'>" + json.expData[i]);
}

When a user clicks on a button this code runs and appends. However if the user clicks on the button again it appends once more and so on.

Is there some way that I could detect that the data has already been appended and only make it add if it's the first time?

Upvotes: 2

Views: 655

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

If you don't have any other element with id contains #text then you can try like this:

if( $('[id^=text]').length ) { // if some element with id text exists 

} else { // not exists

}

Upvotes: 0

Curtis
Curtis

Reputation: 103358

You could store a boolean attribute on the element, such as data-isappended.

if (json.expData[i] != null) {
    var $text = $('#text' + i);
    if (!($text.data("isappended"))){
       $text.append("<br><br><img src='/balloon.png'>" + json.expData[i]);
       $text.data("isappended", true);
    }
}

Upvotes: 1

slash197
slash197

Reputation: 9034

Check if there is an img tag inside #text, that should do it

if ($('#text' + i).find('img').length > 0) 
{
    $('#text' + i).append("<br><br><img src='/balloon.png' />" + json.expData[i]);

}

Upvotes: 0

Related Questions