tallowen
tallowen

Reputation: 4328

Add a DOM element between two children

I want to add a dom element between two children, specifically right before the last one.

<div id='parent'>
    <div class='nav-option'></div>
    <div class='nav-option'></div>
    <div class='nav-option'></div>
    {{I want to insert something here}}
    <div class='nav-option'></div>
</div>

Right now I am using the following code:

$('#add-account').click(function(event){                               
    $('#face').append('<div class="nav-select"></div>');
}); 

But alas this adds the element at the end.

Upvotes: 4

Views: 2781

Answers (4)

Andrew Cooper
Andrew Cooper

Reputation: 32576

Try

$('.nav-option:last').before('<div class="nav-select"></div>');

Upvotes: 0

Sean Adkinson
Sean Adkinson

Reputation: 8605

Check out insertAfter() or insertBefore()

Upvotes: 1

user578895
user578895

Reputation:

jquery has .insertBefore and .insertAfter that both do what you want.

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351516

Try this:

$('div.nav-option:last')
    .before('<div class="nav-select"></div>');

Check these out to read more:

Upvotes: 2

Related Questions