My HTMl is like this
<div class="col-lg-6">
<div class="form-group">
my html-1
</div>
<div class="form-group">
my html-2
</div>
<div class="form-group">
my html-3
</div>
<div class="form-group">
my html-4
</div>
</div>
And I want to insert a new HTML in between my html-4 and my html-3. means the second last position.
How can I make this using JQuery?
I have done something like this
$('#addmore').click(function () {
var newData = My new HTML, I will get here
$('.col-lg-6').append(newData);
});
But this insert the new HTML to the last position. I want it to be inserted at the second last position always. Expected output
<div class="col-lg-6">
<div class="form-group">
my html-1
</div>
<div class="form-group">
my html-2
</div>
<div class="form-group">
my html-3
</div>
<div class="form-group">
my html-new one
</div>
<div class="form-group">
my html-4
</div>
</div>
Given that all the elements have a common class, you could use eq() to place the new content at the required position by index. Try this:
$('#addmore').click(function () {
var newData = '<div>FOO</div>';
$('.col-lg-6 .form-group').eq(-1).before(newData);
});
Example fiddle
Note that providing a negative number to eq() means that you want to count backwards from the end of the matched set.
You can use combination of .last() and .prev()
$('#addmore').click(function () {
var newData = '<div>Whatever</div>';
$('.col-lg-6').find('.form-group').last().prev().after(newData);
});
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With