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

c# - SelectList with Dictionary, add values to the Dictionary after it's assigned to SelectList -

how can i manage url using .htaccess in php? -

ios - I get the error Property '...' not found on object of type '...' -