Reputation: 21
for example if i want to display text from javascript side by side like this
text1 text2 text3
so I typed this code
<p id=displayText> <p>
<script type="text/javascript">
function doSomeThing()
{
//do something
document.getElementById("displayText").innerHTML=text1;
//do something
document.getElementById("displayText").innerHTML=text2;
//do something
document.getElementById("displayText").innerHTML=text3;
}
</script>
I got only
text3
how can I do it.
Upvotes: -1
Views: 8029
Reputation: 1052
<p id=displayText> <p>
<script type="text/javascript">
function doSomeThing()
{
var para = document.getElementById('displayText');
para.innerHTML = para.innerHTML + text1;
para.innerHTML = para.innerHTML + text2;
para.innerHTML = para.innerHTML + text3;
}
</script>
Upvotes: 1
Reputation: 3726
Merely seach for the element once and also pass the values as array (more dynamic and less limited).
<html>
<head>
<script>
function doSomeThing(v){
var tE = document.getElementById('displayText');
if (tE) tE.innerHTML = (v || []).join(' ');
}
</script>
</head>
<body onload = "doSomeThing(['text1', 'text2', 'text3'])">
<span id = 'displayText'></span>
</body>
</html>
Upvotes: 0
Reputation: 57721
+=
can be problematic when used with the non-standard property innerHTML
.
You can avoid using +=
on innerHTML
by using an extra variable:
function doSomeThing()
{
var progress = "";
//do something
progress += text1;
document.getElementById("displayText").innerHTML = progress;
//do something
progress += text2;
document.getElementById("displayText").innerHTML = progress;
//do something
progress += text3;
document.getElementById("displayText").innerHTML = progress;
}
+=
is problematic if you do:
e.innerHTML += '<a href="#">foo';
e.innerHTML += 'bar';
e.innerHTML += '</a>';
The actual output HTML will be <a href="#">foo</a>bar
. How did that happen? Well, when you set the innerHTML to <a href="#">foo
the browser will try to 'fix' it for you so it adds the </a>
to make it valid.
There are also ways to avoid using innerHTML
entirely by using the DOM API proper document.createElement()/createTextNode()
etc.
Upvotes: 2
Reputation: 1219
you set the texts to the same ID. Create 3 ids, not only one.
do this or that :
function doSomeThing()
{
//do something
document.getElementById("displayText").innerHTML = text1;
//do something
document.getElementById("displayText").innerHTML += (" "+text2);
//do something
document.getElementById("displayText").innerHTML += (" "+text3);
}
function doSomeThing()
{
//do something
document.getElementById("displayText1").innerHTML = text1;
//do something
document.getElementById("displayText2").innerHTML = text2;
//do something
document.getElementById("displayText3").innerHTML = text3;
}
//HTML ?
<span id="displayText1"></span>
<span id="displayText2"></span>
<span id="displayText3"></span>
Upvotes: 0