22

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?

0

3 Answers 3

16

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!

2
  • 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
    Commented Nov 26, 2014 at 16:31
  • @WinnerCrespo You additionally might indicate that this is jQuery rather than Vanilla JS
    – wbq
    Commented Feb 22, 2021 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"));
0

Try the following code.

if($('img').length >= 1){
    alert('element exist');
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.