JSFiddle - React, Tailwind, and code Playground
HTML
<ul id="parent-list">
<li id="post-1">Item 1
<div class="num"> 4 </div>
<button class="add">+</button>
<button class="subtract">-</button>
</li>
<li id="post-2">Item 2
<div class="num"> 8 </div>
<button class="add">+</button>
<button class="subtract">-</button>
</li>
<li id="post-3">Item 3
<div class="num"> 10 </div>
<button class="add">+</button>
<button class="subtract">-</button>
</li>
<li id="post-4">Item 4
<div class="num"> 4 </div>
<button class="add">+</button>
<button class="subtract">-</button>
</li>
<li id="post-5">Item 5
<div class="num"> 4 </div>
<button class="add">+</button>
<button class="subtract">-</button>
</li>
<li id="post-6">Item 6
<div class="num"> 4 </div>
<button class="add">+</button>
<button class="subtract">-</button>
</li>
</ul>
CSS
ul {
margin: 0;
padding: 0;
}
li {
list-style-type: none;
border: 1px solid black;
padding: 10px;
margin-bottom: 15px;
}
JavaScript
// grabbing the shared parent of all the buttons we
// wish to get events from. event bubbling allows us
// to identify events from all children of an object
// with a single listener, though if you think about it
// if you click on a button in a box, you're still
// clicking the box since the button is part of what
// makes up that box. getElementById is the best way
// to get elements by an id (ids should be unique - do
// not duplicate them in html)
var theParent = document.getElementById("parent-list");
// add the event listener for user clicks
theParent.addEventListener("click", doSomething);
// handler function called with parent element is clicked
function doSomething(e) {
// since we care about the buttons, we need some
// way to identify button clicks. there's any number
// of ways to do this. the big event (e) properties
// to pay attention to are event.target: the actual,
// individual item clicked on, and event.currentTarget:
// the item the event listener was added. target and
// current target may match, if you clicked on the
// object the listener was added to. if a child was
// clicked, they'll be separate
// for us, every button in the parent is what we want.
// we can check that simply by seeing if the target
// is of the tag typt button.
if (e.target.nodeName === "BUTTON") {
// call the function which handles the actual button
// click, updating the numeric value associated with
// the button passed to it (the button being target)
updateFrom(e.target);
}
}
// this will take a button, find the associated number
// element and update its value. it will check the button
// class to know what to do to the number (add or subtract 1)
function updateFrom(button) {
// the number element is the div with the num class
// in the same parent as the button. querySelector
// finds the first num div and returns it directly
...