Chun
Chun

Reputation: 2270

How to add text before of an element's original text

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

Answers (3)

Travis J
Travis J

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

DinoMyte
DinoMyte

Reputation: 8868

You need to use prepend function. Also , no need of createTextNode.

$("#button").click(function() {
    $( ".text" ).prepend(" Hello");
});

http://jsfiddle.net/8yukxftb/

Upvotes: 1

Andrew Coder
Andrew Coder

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

Related Questions