joel234 joel234 - 1 year ago 101
HTML Question

javascript - remove inline event handlers / attributes of a node

Given an HTML node from the dom,
I need to remove all inline event handlers / attributes such as: onclick, onmouseover, onmousedown etc.

I know that:


returns all the attributes, and I can eliminate some attriubtes, but then there is also attributes like: id, class, name etc.

How do I seperate the two types of attributes?

Completely different approches for solving the problem are also an option.

EDIT: I'm trying to remove only inline events,
and I also need to "save" them elsewhere before deletion, so cloning for complete disposal is not an option

Answer Source

Here you get all element attributes, make an array of em, check in for loop if any attribute starts with on.
Then make an object with name/value of that inline event handler, push it into array, and at the end remove it from the node:

var el = document.getElementById("button1");
var listOfEvents=[];  
var attributes = [];  

for (i = 0; i < attributes.length; i++){
    var att= attributes[i].name; 


     var eventHandlers={};

Check the below snippet

var el = document.getElementById("button1");

var listOfEvents = [];
var attributes = [];

for (i = 0; i < attributes.length; i++) {
  var att = attributes[i].name;

  if (att.indexOf("on") === 0) {
    var eventHandlers = {};
    eventHandlers.attribute = attributes[i].name;
    eventHandlers.value = attributes[i].value;




/* logs   [[object Object] {
  attribute: "onmousedown",
 value: "mouseDown();"
}, [object Object] {
  attribute: "onmouseup",
  value: "mouseUp();"
}, [object Object] {
  attribute: "onclick",
  value: "doSomething(this);"
}] */
  <input id="button1" type="button" onmousedown="mouseDown();" onmouseup="mouseUp();" onclick="doSomething(this);" value="Click Me" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download