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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With