添加单个div元素中显示的所有数字

时间:2014-07-21 03:02:52

标签: javascript html dom sum

我很想知道如何(如果可能的话)添加div中显示的所有数字。

<div> 1 <br /> 2 <br /> 3 <br /> 4 </div>

所以,我想得到div元素中的每个数字并将它们全部添加,因此输出为10。

谢谢!

2 个答案:

答案 0 :(得分:2)

首先,给div id

<div id="myDiv"> 1 <br /> 2 <br /> 3 <br /> 4 </div>

然后:

<script>
// Take the content of the div and split it into an array
var numbers = document.getElementById("myDiv").innerHTML.split(" <br> ");
// Store the length of the array into a variable for repeated use in a loop
var length = numbers.length;
// Create a variable with zero value
var sum = 0;
// Iterate over the elements of the array and ...
// keep adding them to the variable just created
for(var i = 0; i < length; i++){
// Because the elements of the array are strings ...
// Convert them to numbers with the javascript function parseInt()
sum += parseInt(numbers[i]);
}
// Now your sum is ready; alert it or use it in some other way
alert(sum);
</script>

DEMO

答案 1 :(得分:0)

我试过了。

var arr = document.getElementsByTagName('div')[0].textContent.split(' ')

var sum = arr.reduce(function(a,b){return (+a)+(+b)})

console.log(sum) //prints 10
相关问题