Martin AJ
Martin AJ

Reputation: 6707

how to insert something in the beginning of an element?

I have a html like this:

<div id="leftBar">
<span>ad</span>
</div>

Also I have this variable:

var msg = '<span>something</span>';

I want to push msg variable in the beginning of #leftBar element. How can I do that?

This is expected result:

<div id="leftBar">
<span>something</span>
<span>ad</span>
</div>

Noted that .html() won't work as expected. Because $('#leftBar').html(msg); removes the existing <span> which I need to keep it there.

Upvotes: 0

Views: 80

Answers (5)

Dishonered
Dishonered

Reputation: 8861

jQuery prepend() method is the solution. append() method is similar in nature, but it adds the element as the last element.

Upvotes: 1

Lucas Paz
Lucas Paz

Reputation: 815

$(document).ready(function() {
	var msg = '<span>something</span><br>'; // Your variable -- but i added '<br>' --
	$('button[rel="add"]').click(function() {
  	$('#leftBar').append( msg ); // For add after last element within #leftBar
    //$('#leftBar').append( msg ); // For add before first element within #leftBar
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="leftBar">
  <span>ad</span>
  <br>
</div>

<button rel="add">Add +</button>

Upvotes: 1

Priyesh Kumar
Priyesh Kumar

Reputation: 2857

Javascript provides Node.insertBefore() method

You can try this:

var left = document.getElementById('leftBar')
var span = document.createElement("span");
span.innerHTML = "something"

left.insertBefore(span, left.childNodes[0]);

jsfiddle example

Upvotes: 3

Rohith K P
Rohith K P

Reputation: 3561

Use jquery prepend to add new element from beginning(as first child).

var msg = '<span>something</span>';
$('#leftBar').prepend(msg)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div id="leftBar">
<span>ad</span>
</div>

Upvotes: 1

Frank Wisniewski
Frank Wisniewski

Reputation: 1224

leftBar.innerHTML=msg+leftBar.innerHTML;

try a demo : js fiddle

Upvotes: 1

Related Questions