Get element by id add two paragraphs

0

I want to add the two paragraphs with JavaScript (tag or class), but the result is always NaN .

function calcular() {
    const num1 = document.getElementsByClassName("n1").value;
    const num2 = document.getElementsByClassName("n2").value;
    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.n1> 2 </p>
 <p.n2> 5 </p>
 <p id="demo"></p>
 <button onclick="calcular();">Clique para calcular</button>
    
asked by anonymous 25.09.2018 / 01:08

1 answer

1

Your code has three problems:

  • To add classes to HTML, use the class attribute, passing a separated list by spaces, for example, <span class="foo bar baz"></span>

  • To get text from an element other than an entry ( document.getElementByClassName , value , etc) use undefined or input

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 picking up the first element with class n1 and n2, you can get all 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>
    
25.09.2018 / 01:43