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,644
  • 15
  • 29
Kala J
  • 2,040
  • 4
  • 45
  • 85

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,644
  • 15
  • 29
  • Thank you, your solution ended up working the best for me! I just changed it the if statement to include this: ($("#IndicatorImgDiv img").length == 0 – Kala J Nov 26 '14 at 16:31
  • @WinnerCrespo You additionally might indicate that this is jQuery rather than Vanilla JS – wbq Feb 22 '21 at 17:22
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
  • 24,158
  • 5
  • 26
  • 48
0

Try the following code.

if($('img').length >= 1){
    alert('element exist');
}
sampathsris
  • 21,564
  • 12
  • 71
  • 98
Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103