Reputation: 6707
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
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
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
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
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
Reputation: 1224
leftBar.innerHTML=msg+leftBar.innerHTML;
try a demo : js fiddle
Upvotes: 1