Hi!
Please help.
Whats wrong with this code?
<body>
<ul>
<li>10</li>
<li>50</li>
<li>10</li>
</ul>
<div id="total">
</div>
</body>
function computeTotal() {
let total = 0;
console.log($("li"));
$("li").each(() => {
total += parseInt($(this).text(), 10);
});
$("#total").text(`Total: ${total}`);
}
document.addEventListener("DOMContentLoaded", function(){
computeTotal();
});
Hello @AmaliaTadevosyan, you should probably provide a bit more context, as this is not enough information to give you a proper answer.
Is that all the code you have?
Have you imported JQuery?
What’s the output you see when running the code?
The more specific you are, better chances to get help from someone from the community
Hi. Thanks for your reply.
I`ve imported jQuery.
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<ul id='ul'>
<li>10</li>
<li>50</li>
<li>10</li>
</ul>
<div id="total">
</div>
</body>
</html>
function computeTotal() {
let total = 0;
// console.log($("li"));
$("#ul").each(() => {
let li = $("#ul").find("li") // I replaced this keyword with #ul
console.log(li.text())
// total += parseInt($(this).text(), 10);
});
$("#total").text(`Total: ${total}`);
}
document.addEventListener("DOMContentLoaded", function(){
computeTotal();
});
I get this in console.
“105010”
I think the first probleem is with context $(this)
I need to get the individual values of li and add them .
Remember that arrow functions don’t bind their own this
context.
Just ditch the arrow function and use a regular function
instead.
More info here: arrow functions
p.s. I assume your function is inside a script tag, and you copied over inside the html for brevity?
Thank you a lot!!!
Now its workin as expected.
system
Closed
7
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.