akshay
akshay

Reputation: 71

Using javascript to alter span text dynamically and keeping the original text

I have a html page, inside which i have following code snippet, depending on which case we're following:

CASE 1)    <p> <span id ="xyz">  some code here  </span> </p>
CASE 2)    <p> <span id ="xyz">   </span> some code here </p>

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

Upvotes: 1

Views: 26271

Answers (4)

Sundar Singh
Sundar Singh

Reputation: 686

If you are not using jquery :

document.getElementById('xyz').innerHTML=   document.getElementById('xyz').innerHTML + "XYZ";

If you are using jquery:

 $("#xyz").append("xyz");

Upvotes: 1

dheerosaur
dheerosaur

Reputation: 15172

You can append a new text node to span, if you want to keep the old text.

var newtext = document.createTextNode(" new text ");
var spanXyz = document.getElementById("xyz");
spanXyz.appendChild(newtext);

Refer these: createTextNode, appendChild

Edit: To add new text at the beginning, you can use something like

spanXyz.textContent = "new text " + spanXyz.textContent;

Upvotes: 1

Konerak
Konerak

Reputation: 39763

You can just store the current value in a String, and then modify this string:

var mySpan = document.getElementById('xyz').innerHTML;
mySpan += ' and this gets added after the some code here';
document.getElementById('xyz').innerHTML = mySpan;

or faster and more shorthand,

document.getElementById('xyz').innerHTML = document.getElementById('xyz').innerHTML + ' new text after'; //to add text after the existing text
document.getElementById('xyz').innerHTML = 'your new text before ' + document.getElementById('xyz').innerHTML; //to add text before.

Upvotes: 3

Pradeep Singh
Pradeep Singh

Reputation: 3634

document.getElementById('xyz').innerHTML = 'some code here' + 'dynamically code';

or

document.getElementById('xyz').innerHTML = 'dynamically code' + 'some code here' ;

Upvotes: 0

Related Questions