Skip to content
Advertisement

How to select span within a dynamically generated button?

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.

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement