Skip to content
Advertisement

how to count clicks on an element other than a button?

I have an empty box in the footer section, which is situated in the div

<footer>
<div>
</div>
</footer>

I would like to write a function in javascript that would count the number of clicks in the div, and display the number of clicks in the same div. I am wondering how to achieve this without touching the html. I have seen how to achieve this with a button, but how can I achieve this with a div ? thanks

Advertisement

Answer

Use .querySelector, if you dont to want add any ID or Class.

var elem = document.querySelector('footer div');

let countClicks = 0;

elem.onclick = function() { 
  countClicks++;
  elem.textContent = countClicks
};
div {
padding:10px;
background: #339900; 
color: #fff;
font-size: 44px;
}
<footer>
  <div></div>
</footer>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement