Reputation: 2270
I'm trying to add some text before of the original text of an element.
Now, I know to insert text after the original content, I can do it using createTextNode
like the example below:
$("#button").click(function() {
$( ".text" ).append( document.createTextNode( " Hello" ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="button">Button</button>
<div class="text"> Some random text</text>
But how can I add it before?
Upvotes: 0
Views: 67
Reputation: 82337
Can't you also just alter the text there? It doesn't seem from your example that there is anything wrong with
$( ".text" ).text(function(i,txt){ return "Hello " + txt });
Upvotes: 1
Reputation: 8868
You need to use prepend function. Also , no need of createTextNode.
$("#button").click(function() {
$( ".text" ).prepend(" Hello");
});
Upvotes: 1
Reputation: 1058
.prepend
is the function you want.
$("#button").click(function() {
$( ".text" ).prepend( document.createTextNode( " Hello" ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="button">Button</button>
<div class="text"> Some random text</text>
Upvotes: 1