1

I would like to use jQuery to insert an html element inside another element and at a particular position.

I've found a way I can do it in Javascript but was wondering if there's a shorter 'one line of code' way of doing it in jQuery.

var container = document.getElementById("container");
container.insertBefore( html, container.children[0] );

Many thanks in advance

1

2 Answers 2

3

Use the selector for the n-th child of a given kind and the before method (assuming your new content comes in html) :

$("#container > div:nth-of-type(42)").before(html);

If you want to insert a new element as the first or last child of a container, there is another api option:

$("#container").append( html );
$("#container").prepend( html );

(For the sake of completeness, append / prepend are the links into the jQuery API docs)

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @collapsar. Thanks for your reply. Before I take your suggestion as my way forward is there not anything like (the following is pretend/dreamed up jQuery): $("#container").insertAt( myHtml, 0 )
In fact it is: $($("#container > div")[41]).before(html); :-). Note the index shift, if you prefer to code this way (however, I honestly see no reason why that should be the case). Also note that wrapping the target element in another jQuery element comes handy in case the targeted position does not exist in the Dom.
0

If you want to add an element inside an other with jquery, you have to do like this :

$('#container').append(html);

1 Comment

Hi @loloMinou. Thank you for your reply. However append just puts the inserted content at the end of childlist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.