Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all li element to calculate using JavaScript

This list was generated using input tag and appending the element to ul :

<ul id ="add">
    <li>3</li>
    <li>4</li>
    <li>*</li>
    <li>5<li>
    <li>+<li>
    <li>3</li>
<ul>

This is list now I would like to iterate over it so that on the console I get 34*5+3 which can calculate using JavaScript, but how to get the value of all Li to tag together so that it is able to calculate:

The complete code is from which I would like to do the calculation :

<!DOCTYPE html>
<html>
    <head>
        <title>solve</title>
       <script>
        document.addEventListener('DOMContentLoaded',()=>{
            document.querySelector('#submit').onclick =()=>{
                const li = document.createElement('li');
                li.innerHTML = document.querySelector('#number').value;
                document.querySelector('#add').append(li);
                return false;
            };
        });
       </script>

       <style>
           li{
               list-style-type: none;
               display: inline;

           }
       </style>
    </head>
    <body>

        <div id="user-input">
            <ul id="add">

            </ul>
        </div>
        <div>
           <form>
                <input type="text" id="number">
                <input type="submit" id="submit">
           </form>

        </div>
    </body>
</html>
like image 428
green seek Avatar asked Mar 05 '23 11:03

green seek


1 Answers

You can use document.querySelector and textContent to get the text which will be a string then use eval to calculate it.

let m = [...document.querySelector("#add").children];
let val = '';
m.forEach(function(item) {
  val += item.textContent;

})

console.log(eval(val)) //34*5+3
<ul id="add">
  <li>3</li>
  <li>4</li>
  <li>*</li>
  <li>5</li>
  <li>+</li>
  <li>3</li>
</ul>
like image 90
brk Avatar answered Mar 15 '23 16:03

brk