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?
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!
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With