joel234 joel234 - 7 months ago 19
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:

document.getElementById("some_id").attributes


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

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 = [].slice.call(el.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;
     listOfEvents.push(eventHandlers);
     el.attributes.removeNamedItem(att);             
   }     
} 

Check the below snippet

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

var listOfEvents = [];
var attributes = [].slice.call(el.attributes);

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

  if (att.indexOf("on") === 0) {
    console.log(att);
    var eventHandlers = {};
    eventHandlers.attribute = attributes[i].name;
    eventHandlers.value = attributes[i].value;
    listOfEvents.push(eventHandlers);
    el.attributes.removeNamedItem(att);

  }


}


console.log(listOfEvents);


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