javascript - Append HTML element if it doesn't already exist -


<p id="main_class">     <span class="new_class"></span> </p> 

in following code wanted append <span class="new_class"></span> if doesn't exists in main_class , if exists prevent appending div.

i tried following code

jquery(".main_class").append('<span class="new_class">hello</span>'); 

you can use :not , :has selectors together:

jquery("#main_class:not(:has(.new_class))").append('<span class="new_class">hello</span>'); 

note main_class id, select hash (#)

jsfiddle


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -