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 - Unusual behaviour when drawing lots of images onto a large canvas -

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

javascript - Chart.js - setting tooltip z-index -