Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Change all onclick to event listeners

We recently introduced the nonce content security policy in our software. The problem is that we have hundreds of HTML elements which execute inline Javascript with onclick events and we don't want to accept 'unsafe-inline' anymore.

Is there any way of getting all the elements from a page with onclick attribute set, read the code that they execute it and add something like

$(element).click(function(){
   doAction();
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The onclick attribute is executed before any other click event handler in your JS.

function doSomething() {
  console.log('I do something')
}

var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++) {
  if (typeof allElements[i].onclick === 'function') {
    allElements[i].addEventListener("click", function(e) {
      console.log('Before I do something');
    });
  }
}
<div onclick="doSomething()">Click me to doSomething</div>

A trick workaround would be doing something like this :

function doSomething() {
  console.log('I do something')
}

var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++) {
  if (typeof allElements[i].onclick === 'function') {
    allElements[i].addEventListener("mousedown", function(e) {
      console.log('Before I do something');
    });
  }
}
<div onclick="doSomething()">Click me to doSomething</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!