Your question asks how to get the id
of the clicked element, but your explanation asks how to get the sum of the items added to the list. I'll answer the how to get the id
question below, but the final answer shows how to get the sum.
- First, don't use inline HTML event attributes (i.e.
onclick
).
Here's why.
- Next, if the element doesn't have an
id
, then there's nothing to
get.
- Just use
this
to refer to the element that caught the
event.
Now, you've got some other issues to correct as well...
- "Topics" shouldn't be in the list, it should be a title above it.
- Don't use an HTML tag because of the way it formats its content (i.e.
<h3>
). Use CSS for all formatting. HTML is for describing what the
content is.
- Nothing is allowed after
</body>
except </html>
so move that
<script>
you have there to just prior to the </body>
, which will
then place it just after the </script>
you have for the button
click
code. Given that the two <script>
elements will then be
right next to each other, just combine them into a single <script>
.
type="text/javascript"
hasn't been necessary for years on
<script>
elements.
.innerHTML
has performance and security implications, so don't use
it when the string you are working with doesn't contain any HTML, use
.textContent
instead and also use .textContent
instead of
.innerText
, which is non-standard.
- Your code refers to an element with an
id
of sum
, but you don't
have that in your code.
- Don't use self-terminating tags. It buys you nothing and adds
confusion.
.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type='number' id='input'> <!-- You only want numbers so use a number input -->
<input type='button' value='add to list' id='add' disabled="disabled">
<div class="title">Topics</div>
<ul id='list'></ul>
<button id="something">Click Here To See The Sum</button>
<script>
// Get references to the elements you'll use repeatedly:
let list = document.getElementById("list");;
let btn = document.getElementById("something");
let input = document.getElementById("input");
let add = document.getElementById("add");
var sum = 0;
// Set up events in JavaScript, not HTML:
input.addEventListener("input", enableDisable);
btn.addEventListener("click", sumvar);
add.addEventListener("click", function() {
var li = document.createElement("li");
li.textContent = input.value;
sum += +input.value; // The prepended + converts the string to a number
list.appendChild(li);
input.value = ""; // Clear out the input
add.disabled = "disabled";
});
function enableDisable(){
// Disable/Enable the Add button depending on if there is input to add
if(this.value === ""){
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
function sumvar() {
alert("The sum of your numbers is: " + sum);
}
</script>
</body>
</html>