Problem: How to update the innerHtml of a span within a dynamically generated button using only JavaScript?
I'm building a 'like' feature (think social media) where users can like/unlike posts, but I can't figure out how to select the value of the specific span the user clicks on. I've been only able to find jQuery solutions using .find('span')
const htmlBtn = `<button class="count"><span>0</span></button>`;
const create = document.getElementById("create");
create.addEventListener("click", (e) => {
const container = document.createElement("div");
container.className = "container";
container.innerHTML = htmlBtn;
document.getElementById("app").append(container);
});
const app = document.getElementById("app");
app.addEventListener("click", (e) => {
const btn = e.target;
/*
each time someone click nth button, span within nth button increments by 1
let count = document.querySelector("span").innerHTML;
count++;
document.querySelector("span").innerHTML = count;
*/
});
<button id="create">Create</button>
<div id="app"></div>
Expected outcome: User clicks the button to increment the span of only that button by 1.
e.target.children will give you an array of all the children of button and the 0th index of the array should be your span element which you can then edit normally using the innerHTML method.
In your case,
let count = parseInt(e.target.children[0].innerHTML);
e.target.children[0].innerHTML = count + 1;
create.addEventListener("click", (e) => {
const container = document.createElement("div");
container.className = "container";
container.innerHTML = htmlBtn;
document.getElementById("app").append(container);
container.addEventListener("click", (e) => {
const value = +e.target.innerHTML;
e.target.innerHTML = (value + 1).toString();
});
});
The methods querySelector() and querySelectorAll() can be called on a specific parent element, similar to find() in jQuery.
Make sure to use e.currentTarget and not e.target in the event listener, in order to refer to the element that handles the event and not to any child element.
Example - click any of numbers to increment.
function clickToIncrement(e) {
const innerSpan = e.currentTarget.querySelector('span');
if (innerSpan) {
innerSpan.textContent++;
}
}
document.getElementById('div1').addEventListener('click', clickToIncrement);
document.getElementById('div2').addEventListener('click', clickToIncrement);
<div id="div1">
<span>0</span>
</div>
<div id="div2">
<span>0</span>
</div>