yonige yonige - 5 months ago 11
HTML Question

Add +1 to p everytime the divis clicked

<div id="main">

<div id="rating">

<div> <img src=""/> <p>0</p> </div>

</div>

<div id="main">


I want to increment the number inside p everytime I click on the inner div. I've tried some methods. But they only work with buttons, and I don't want to change the HTML.

Answer

Simply bind a click event handler and update text inside the p tag on click.

// add click event handler to the div
document.getElementById('rating').addEventListener('click', function() {
  // get p element inside the div
  var p = this.querySelector('p');
  // update the content
  p.textContent = Number(p.textContent) + 1;
});
<div id="main">
  <div id="rating">
    <div>
      <img src="" />
      <p>0</p>
    </div>
  </div>
</div>