-1
I’m doing a simple summing function, which takes 2 html numbers, sums and should include a div for the result.
<section class="container">
<h1 class="title">Somando os valores
<p class="firstNumber">1<p>
e valor
<p class="secondNumber">2<p>
</h1>
<h2 class="results">Resultados:
</h2>
</section>
let firstNumber = document.querySelectorAll(".firstNumber");
let secondNumber = document.querySelectorAll(".secondNumber");
let resultsDiv = document.querySelectorAll(".results")[0];
function createResults(text, result, className) {
console.log("result" + result);
const newDiv = document.createElement('p');
newDiv.className = className;
newDiv.textContent = text + result;
resultsDiv.appendChild(newDiv)
}
let secondSumMethod = (x, y) => {
return x + y
}
let secondSumMethodResult = secondSumMethod(firstNumber, secondNumber);
createResults("second sum method: ", secondSumMethodResult, secondSumMethodClassName);
But when I try to get the result that in the case should be a number, I’m getting the following:
second sum method:[object NodeList][object NodeList]
I’ve tried to do result[0]
and it didn’t work either, so I tried to create a method
result = nodeToArray(result);
function nodeToArray(result) {
for (i = 0; i < result.length; i++) {
console.log(result[i]);
}
return Array.from(result);
}
But then he returned:
[,o,b,j,e,c,t, ,N,o,d,e,L,i,s,t,],[,o,b,j,e,c,t, ,N,o,d,e,L,i,s,t,]
What would be missing from my code?
Just telling you,
document.querySelectorAll
returns a arraylist ofNodeList
, if you want to "catch" the contents of the first element dodocument.querySelectorAll(".firstNumber")[0].textContent
, if you want to perform mathematical operations, convert from string for number using the+
:let firstNumber = +document.querySelectorAll(".firstNumber")[0].textContent;
– Cmte Cardeal
That’s right, thank you very much !
– Sabrina