21

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?

Winner Crespo
  • 1,534
  • 13
  • 29
Kala J
  • 2,028
  • 4
  • 43
  • 81

3 Answers3

15

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!

Winner Crespo
  • 1,534
  • 13
  • 29
1

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"));
PeterKA
  • 22,910
  • 4
  • 23
  • 48
0

Try the following code.

if($('img').length >= 1){
    alert('element exist');
}
sampathsris
  • 20,518
  • 11
  • 61
  • 93
Imesh Chandrasiri
  • 5,428
  • 13
  • 56
  • 101