从HTML字符串中获取所有内联事件

Get all inline events from HTML string

本文关键字:事件 获取 HTML 字符串      更新时间:2023-09-26

我试图从HTML <body>字符串中获得所有内联事件标签的列表,我如何才能做到这一点?

的例子:

 <a onclick='foo()'></a>

我想提取onclick='foo()'

是否可能使用REGEX或任何其他替代方案?

这里有一个。事件将是第1组:

<'w+[^>]+(on[a-z]+=["'][^"']+["'])[^>]*>

应该让浏览器进行解析,例如:

var doc = document.implementation.createHTMLDocument('');
doc.documentElement.innerHTML = '<body onload="alert(1)"></body>'; // your string here

然后使用DOM方法获取on*属性:

var attributes = Array.prototype.slice.call(doc.body.attributes);
for (var i = 0; i < attributes.length; i++) {
    if (/^on/.test(attributes[i].name)) {
        console.log(attributes[i].name, attributes[i].value);
    }
}