Wold
Wold

Reputation: 972

Inserting content into the DOM

I know that jQuery has the append() function which allows you to place content at the end of an element, but is there a way to insert it at the top or somewhere in between, with a location specified as a parameter?

This is how I've been doing it:

var newContent = "<div>Top</div>";
var content = $('#myDiv').html();
$('#myDiv').html(newContent + content);

I am wondering if there is a function that allows you to insert at the top of an element and/or if there is a function that allows you to insert content into a certain location, where you might pass in a child-element and the content would be placed right after/before that element, even though it might not be at the top or the bottom of the element.

Thanks and any help or guidance is appreciated.

Upvotes: 0

Views: 65

Answers (5)

amahrt
amahrt

Reputation: 523

jQuery has built in functions like before() and after().

Example:

$('#your-element').after('<span>I am after that element with the ID #your-element</span>');

Also there are functions like prepend() to add elements as child but at the beginning of the parent, and append() to add it after the parent's last child.

Example:

$('#your-element').prepend('<span>Im the first element in the #your-element element.</span>');

Upvotes: 1

Girish
Girish

Reputation: 12127

Use prependTo() function to prepend element inside <selector>

var newContent = "<div>Top</div>";
$(newContent).prependTo('#myDiv')

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

You have the following methods:

append(); // Appends to the element
prepend(); // prepends to the element
insertAfter(); // inserts a sibling after the element
insertBefore(); // inserts a sibling before the element

In your case you want to utilize prepend().

var newContent = "<div>Top</div>";
$('#myDiv').prepend(newContent);

Upvotes: 4

Milind Anantwar
Milind Anantwar

Reputation: 82251

You can simply use .prepend():

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

$('#myDiv').prepend(newContent)

Upvotes: 0

mjk
mjk

Reputation: 2453

Yep! insertBefore and before both let you insert before an element, using slightly different syntax depending on your preference.

insertBefore:

$("<div>Top</div>" ).insertBefore( "#myDiv" );

before:

$( "#myDiv" ).before( "<div>Top</div>" );

Upvotes: 1

Related Questions