Home > OS >  Display in html an element from an array in javascript
Display in html an element from an array in javascript

Time:07-26

I have created a function that generates an array in javascript. Once the array as been created i would like to display some of its items in html, however without using the document.getElementById() in javascript. Is there a way to select an item from the array directly in html?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Distance calculator</title>

<script>
let myArray = [5, 7, 9]
var soluzioni =[]
    

function calcolo(){
    for(let i=0; i<myArray.length; i  ){
        var y = myArray[i];
        var risultato = y*y;
        soluzioni.push(risultato);
    document.getElementById('Calcolo').innerHTML =  soluzioni[0]   "<br>";    
    }
     
}
    

</script>

    
</head>
<body>
    <div id="posizione">
        <button onclick="calcolo();"> calcola</button>
    </div>
    <br>
    
    <div id="Calcolo">
        
    </div>

</body>
</html>

I would like something like:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Distance calculator</title>

<script>
let myArray = [5, 7, 9]
var soluzioni =[]
    

function calcolo(){
    for(let i=0; i<myArray.length; i  ){
        var y = myArray[i];
        var risultato = y*y;
        soluzioni.push(risultato);   
    }
     
}
    

</script>

    
</head>
<body>

    <div id="posizione">
        <button onclick="calcolo();"> calcola</button>
    </div>
    <br>
    
    <div id="Calcolo">
        <p> soluzioni[0] </p>
    </div>

</body>
</html>

CodePudding user response:

I agreed with @David. Plus, even if you could (horribly) writing the actual content of soluzioni[0] when you parse the <p> tag, it won't automatically update once you execute the function calcolo, and you will also end up with spaghetti code.

I would strongly suggest to use Svelte, since it is "reactive" in exact that way; but framework such as the one mentioned by @David are a good solution.

Otherwise, in vanilla JS, the proper approach is using a reference to a node (using method such as getElementById or a querySelector* ones), and could looks like something as the code below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Distance calculator</title>    
</head>
<body>
    <div id="posizione">
        <button> calcola</button>
    </div>
    <br>
    
    <div id="Calcolo">
        <p></p>
    </div>
    <script>
      let myArray = [5, 7, 9];

      const calcolo = (arr) => arr.map(y => y * y);
      
      let button = document.querySelector("#posizione > button");
      let output = document.querySelector("#Calcolo > p");
      
      button.addEventListener("click", () => {
        let soluzioni = calcolo(myArray);
        output.textContent = soluzioni[0];  
      });
    </script>
</body>
</html>

  • Related