nicholaswmin
nicholaswmin

Reputation: 22939

Append something as nth child - If only child append as first child

How can I append something as the nth child of a div with id 'selected_panel'

i.e: I don't know which types of HTML elements will be the children so i cannot really use something like:

// This looks only for children with type ''div''
$("#selected_panel div:nth-child(1)")

Upvotes: 0

Views: 2284

Answers (4)

Wojciech Mleczek
Wojciech Mleczek

Reputation: 1634

Create plugin:

$.fn.nthorfirst = function (path, i) {
    var elems = this.find(path);
    if (elems.length > i) return elems.eq(i);
    else return this;
}

$('#selected_panel').nthorfirst('> *', 2).before("<div> Done! </div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="selected_panel">
    <p>Lorem</p>
    <div>Lipsum</div>
    <a href="#"> Dolor </a>
</div>

Upvotes: 1

This will insert an element as the nth child if there are at least n-1 elements, else it will be inserted at the end.

var n = 7;
var len = $("#selected_panel").children().length;
var index = (len >= n) ? n-1 : len;
$("#selected_panel").find(':nth-child(' + index + ')').after($('<div>bar</div>'));

http://jsfiddle.net/jtr2wd7b/1/

Upvotes: 1

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

You can use the ':nth-child(1)` without any tags.

$("#selected_panel :nth-child(1)")

Upvotes: 3

K K
K K

Reputation: 18099

You can try this:

JS:

$(document).ready(function () {
    var e = $('<div>New Child</div>'); //New child to be added
    var c = $('#selected_panel').children(); //gets the children of div
    if (c.length) {                         //if there are children inside the div
        var l = c.length;
        $('#selected_panel>*:nth-child(' + l + ')').after(e);
    } else {                                //if there is no child
        $('#selected_panel').append(e);
    }
});

You can change the value of l according to the position where you want to append the new child.

Sample HTML:

<div id="selected_panel">
    <div>AADsd</div>
    <div>AADssdd</div>
    <div>asdfAADsd</div>
    <div>AADssdd</div>
    <div>AADsdsd</div> <span>sdfsadfsa</span>
 <span>sert3dfsadfsa</span>
 <span>s457647dfsadfsa</span>

    <p>er</p>
</div>

Demo: http://jsfiddle.net/GCu2D/350/

Upvotes: 1

Related Questions