How to apply the same onClick event to hundreds of DIVs with the same class?

I need to copy the content of more than 200 different divs, one at a time, by simply clicking them, sharing the same class.

This is the code I always use for this purpose:

function copyText(element) {
  var range, selection, worked;

  if (document.body.createTextRange) {
    range = document.body.createTextRange();
  } else if (window.getSelection) {
    selection = window.getSelection();        
    range = document.createRange();
  try {
  catch (err) {
    alert('unable to copy text');

And then I add this line to my div tags:
<div onclick="copyText(this)" class="anything"></div>

This works perfectly and it’s very easy to do when they are a dozen of divs.
But my files keep growing and now my divs are more than 200 on each file, so I want to do this in a more professional and practical way.

I wonder how can I add this function in a proper and smart way to all these divs, to copy the different content of each div, one at a time, by just clicking the div I need to copy at that moment, as all these divs share the same class, but of course I have other divs not sharing the same class, which I don’t want to copy.

114 thoughts on “How to apply the same onClick event to hundreds of DIVs with the same class?”

Leave a Comment