我正在尝试添加具有相同类的所有元素。 像这样:-
<span class="total"> 4</span>
<span class="total"> 8</span>
<span class="total"> 5</span>
<span class="total"> 3</span>
<span class="total"> 9</span>
<span class="total"> 12</span>
<span class="total"> 34</span>
<span class="total"> 22</span>
要显示在<p id="answer"></p>
答案 0 :(得分:0)
您可以尝试以下操作:
let total = 0;
document.querySelectorAll('.total').forEach(span=>{
total += ~~span.textContent;
});
document.querySelector('#answer').textContent = total;