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?
.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>
You need to use prepend function. Also , no need of createTextNode.
$("#button").click(function() {
$( ".text" ).prepend(" Hello");
});
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 });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.