javascript - jquery is not working when append a new div -


this question has answer here:

i have element in div, using class have jquery defined. when add(append) new div same class, jquery not working.

in snippet below, elements under 'old' hard coded , jquery works fine elements under 'new' appended , same jquery not working.

$(".ele").on("click", function() {    $(this).hide();  });  $("#more").on("click", function() {    $("<div class='ele'></div>").appendto("#all");  });
.ele {    width: 20px;    height: 20px;    margin: 10px;    background-color: #bbb;    display: inline-block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="more" style="cursor: pointer">click add box</div>  <br/>  <div id="all">    <div>instruction: click boxes hide</div>    <div>old elements:</div>    <div class="ele"></div>    <div class="ele"></div>    <div class="ele"></div>    <br/>    <br/>    <div>new elements:</div>  </div>

i want append div same class on predefined jquery work. please help.

your approach close working, if element gets generated dynamically, have call existing parent , put target element in on() function... otherwise won't recognized.

for better explanation, see: http://api.jquery.com/on/

$("#all").on("click",".ele", function() {    $(this).hide();  });  $("#more").on("click", function() {    $("<div class='ele'></div>").appendto("#all");  });
.ele {    width: 20px;    height: 20px;    margin: 10px;    background-color: #bbb;    display: inline-block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="more" style="cursor: pointer">click add box</div>  <br/>  <div id="all">    <div>instruction: click boxes hide</div>    <div>old elements:</div>    <div class="ele"></div>    <div class="ele"></div>    <div class="ele"></div>    <br/>    <br/>    <div>new elements:</div>  </div>


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -