Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert HTML at specific position JQuery

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>
like image 637
None Avatar asked Sep 11 '26 06:09

None


2 Answers

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.

like image 80
Rory McCrossan Avatar answered Sep 12 '26 19:09

Rory McCrossan


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

like image 44
Satpal Avatar answered Sep 12 '26 21:09

Satpal