简体   繁体   中英

Way to remove javascript events from the html tags?

Is there any way to remove all the javascript events from the html tags?

For example

<img src=" " onclick="" />
<img src=" " onerror="" />

I want to strip onclick and onerror from these tags. As in the example, I want to strip all the javascript events from the html tags.

You can do this to clear the events :

// get all img elements
var imgElements = document.getElementsByTagName('img');
// loop elements
for (var i = 0; i < imgelements.length; i++) { 
  // clear handler
  imgElements[i].onclick = null;
  // add other handlers here
  // imgElements[i].<here> = null;
}

Docs for getElementsByTagName() here

Update 1 - All elements on document

If you want to get all of the elements on the document then use document.getElementsByTagName('*')

Update 2 - All events

To clear all events have a look at this answer

You can check out jquery .unbind() .

Reference: http://api.jquery.com/unbind/

It's also easy to put the event handler back when you need it using .bind()

by using jquery:

$('*').each(function(){      
    if ($(this).is('img')) {
        $(this).unbind('click');
    }
});

if you want to only remove the specific function onclick event, you can do like this..

 $(this).unbind('click', FunctionName);

As of jQuery 1.7 , you are also able use $.on() and $.off() for event binding, so to unbind the click event, you would use the simpler and tidier:

$(this).off('click');

Try this javascript in the document.onload event (untested):

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++) {
    all[i].onclick = undefined;
    all[i].onerror = undefined;
}

If you mean "remove" as in physically remove them from the page source, you could probably use a regular expression to get most of them, replacing pattern on(\\w+?)="(.*?)" with a blank string. (I've not tested, it may need tweaking)

If you mean "remove" as in logically remove them by unbinding them, you could use the unbind() method in jQuery, or set each event to null looping through the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM