简体   繁体   中英

Using span tag in JavaScript to modify contents inside html <p> tags

Say we have the following code:

<html>
<body>
<p id="income"></p>
</body>
<script>
var income = 95350.23
document.getElementById("income").innerHTML = 'Income <span style = "float:right;">' + income + '</span>'
</script>
</html>

How do we fix this code? I'm trying to make the contents inside the

tag state: "Income" on the left and 95,350.23 on the far right.

Thank you!

You have syntax errors in your code, you forgot to concatenate income with the rest of the string with + .

 var income = 95350.23; document.getElementById("income").innerHTML = 'Income <span style = "float:right;">' + income + '</span>'; 
 <p id="income"></p> 

var income = 95;   
document.getElementById("income").innerHTML = "Income " + "<span style = 
"+"float:right;"+">"+income+"</span>"

change the initialization of income

Here I'm extending the answer from @julekgwa with the method toLocaleString , which prints out a number in local format. Please pay attention to the output (comma and point). As I understand, this is a requirement in your question.

 var income = 95350.23; document.getElementById("income").innerHTML = 'Income' + '<span style = "float:right;">' + income.toLocaleString('en-US') + '</span>'; 
 <p id="income"></p> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM