JQuery: get index of dynamically added div in another div?
I am adding divs to a div container. I want to show the index of the child div on the left. How can i do this?
$('#btn').on('click', function() {
$('#container').append('<div class="section">' + $(this).index('.container') + ' B</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="container">
<div class="section">A</div>
<div class="section">B</div>
</div>
<button id="btn">Click Me!</button>
source to share
The problem is $(this).index('.container')
, your handler is this
referencing a button that is not a member of the selector .container
, so it returns-1
So, one solution is to add a new one div
, then find its index, I think you want the index to be based on a div with classsection
$('#btn').on('click', function() {
$('<div />', {
"class": 'section'
}).appendTo('#container').html(function() {
return $(this).index('.section') + ' B'
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="container">
<div class="section">A</div>
<div class="section">B</div>
</div>
<button id="btn">Click Me!</button>
Or you can find an already existing item count with a class section
and use that as the index for the new item
$('#btn').on('click', function() {
$('#container').append('<div class="section">' + $('#container .section').length + ' B</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div class="section">A</div>
<div class="section">B</div>
</div>
<button id="btn">Click Me!</button>
source to share
$(this).index('.container')
will try to find the index of the pressed button in the container. Which doesn't exist, because of which it returns -1
.
You need to use the length of the number of elements in the container as the index value here:
$('#container > .section').length;
Demo:
$('#btn').on('click', function() {
$('#container').append('<div class="section">' + $('#container > .section').length + ' B</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="container">
<div class="section">A</div>
<div class="section">B</div>
</div>
<button id="btn">Click Me!</button>
source to share