How to check if append element exists?

I have something like this:

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

Now it adds a red dot image when I click on the button, but when I click on the button again, it adds it again. I just want it to appear once when I press the button. How to check if an added item exists or not?

+8
javascript jquery html
source share
3 answers

Just do the following:

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 is JSFiddle!

+10
source share

Try using the following code.

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

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
source share

All Articles