javascript - Select dynamically created element -
i created div dynamically , attached div. i'm trying add data query , load text field. but, i'm unable select dynamically created elements because not visible in dom, since loaded. have fiddle
<div id="parent"> <input id='childbutton' type="button" value="add"/> <div id="child" data-row="0"> <input type="text" value="" /> </div> </div> var rownum = 0; $('#parent').on('click', '#childbutton', function() { var clone = $('#child').clone().attr('data-row', ++rownum); $('#parent').append(clone); console.log($('#child[data-row=1]').length); });
the problem id selector, return first element given id. in case creating multiple elements id child. #child
return first child
element, applying data-row
rule filter out selected element getting 0
result.
the solution use class instead of id select element
var rownum = 0; $('#parent').on('click', '#childbutton', function() { var clone = $('#child').clone().attr('data-row', ++rownum).removeattr('id'); $('#parent').append(clone); //here clone refers dynamically create element //but if want fetch element using selector snippet.log($('.child[data-row=1]').length); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <div id="parent"> <input id='childbutton' type="button" value="add" /> <div id="child" class="child" data-row="0"> <input type="text" value="" /> </div> </div>
Comments
Post a Comment