Your code has three problems:
To add classes to HTML the attribute is used class
, passing a space-separated list, for example, <span class="foo bar baz"></span>
document.getElementByClassName
returns a Nodelist, i.e., a list of elements, when accessing the property value
returns undefined
To get the text of an element that is not an input (input
, select
, etc) use innerText
or innerHTML
Corrected code:
function calcular() {
const num1 = document.getElementsByClassName("n1")[0].innerText;
const num2 = document.getElementsByClassName("n2")[0].innerText;
const elemResultado = document.getElementById("demo");
const soma = parseInt(num1)+parseInt(num2);
elemResultado.innerText = "O resultado é :"+soma;
}
input{
size: 50px;
}
body{
margin-top: 100px;
margin-left: 100px;
margin-bottom: 100px;
margin-right: 100px;
border-style: double;
}
h1{
font-family: algerian;
}
p#demo{
background-color: white;
font-size: 30px;
}
<h2>Some os valores abaixo:</h2>
<p class="n1"> 2 </p>
<p class="n2"> 5 </p>
<p id="demo"></p>
<button onclick="calcular();">Clique para calcular</button>
An idea that might be interesting, instead of taking the first element with class n1 and N2, you can take all the elements with class n and use a loop to sum them up:
function calcular() {
const num = document.getElementsByClassName("n");
const elemResultado = document.getElementById("demo");
let soma = 0;
for (let n of num) {
soma += parseInt(n.innerText);
}
elemResultado.innerText = "O resultado é :"+soma;
}
input{
size: 50px;
}
body{
margin-top: 100px;
margin-left: 100px;
margin-bottom: 100px;
margin-right: 100px;
border-style: double;
}
h1{
font-family: algerian;
}
p#demo{
background-color: white;
font-size: 30px;
}
<h2>Some os valores abaixo:</h2>
<p class="n"> 2 </p>
<p class="n"> 5 </p>
<p class="n"> 3 </p>
<p id="demo"></p>
<button onclick="calcular();">Clique para calcular</button>
You’re taking the elements the wrong way, take a look at your HTML.
– LeAndrade
getElementsByClassName
returns a "list" of elements and not just 1– Isac
how do I return 1?
– BKiller
@Bkiller
getElementsByClassName
always returns a "list", but if you are only interested in the first element you can access it through the array syntax with[0]
, thusdocument.getElementsByClassName("n1")[0].value
– Isac