Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if append element already exists? [duplicate]

I have something like this:

if (result.Indicator == 1) {
    $('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
}

Now, this appends an image of a red dot when I click on a button but when I click on a button again, it appends it again. I just want it to appear once when I click on a button. How can I check if the appended element already exists or not?

like image 484
Kala J Avatar asked Nov 26 '14 03:11

Kala J


2 Answers

Just do the next:

Html code

    <input id="addImage" type="button" value="Add image"/>
    <div id="IndicatorImgDiv">
    </div>

Javascript code

    $("#addImage").click(function(){
         if($("#IndicatorImgDiv img").length == 0){
             $('#IndicatorImgDiv').append($('<img />').attr("src", "http://www.thepointless.com/images/reddot.jpg"));
         }
    });

Here the JSFiddle!

like image 119
Winner Crespo Avatar answered Oct 06 '22 13:10

Winner Crespo


Just change:

$('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));

To:

$('#IndicatorImgDiv').find('img[src$="reddot.png"]').length ||
    $('#IndicatorImgDiv').append($('<img />').attr("src", "/Content/images/reddot.png"));
like image 39
PeterKA Avatar answered Oct 06 '22 12:10

PeterKA