测试 DOM 中所有元素节点的属性是否存在
我试图查找页面内的任何标签是否包含 js 事件属性,例如 onload、onunload、onfocus 等,... 为此,我有一组事件要检查(我想我已经全部拥有了):
var attr = [
"onLoad",
"onunload",
"onclick",
"ondblclick",
"onmousedown",
"onmouseup",
"onmouseover",
"onmousemove",
"onmouseout",
"onfocus",
"onblur",
"onkeypress",
"onkeydown",
"onkeyup",
"onsubmit",
"onreset",
"onselect",
"onchange"];
然后我获取所有 elementsByTagName 并想要检查它们的属性:
var getAttrs = function() {
var i = 0,
j,
all = document.getElementsByTagName('*'),
max = all.length,
eventsLen = attr.length;
for (; i < max; i++) {
console.log('iterating through objects');
for (j = 0; j < eventsLen; j++) {
if (all[i].hasAttribute(attr[j])) {
console.log('found an instance of an intrinsec event', attr[j]);
}
}
}
};
这不起作用,我没有得到任何我想找到的属性。
此外,我想找到使用 javascript 的所有标签中的所有属性:(例如 中)知道如何将其添加到函数的逻辑中吗?
谢谢!
I'm trying to find if any of the tags inside a page contain a js event attribute, such as onload, onunload, onfocus etc, ...
To do so I have an array of events to check for (I think I have them all):
var attr = [
"onLoad",
"onunload",
"onclick",
"ondblclick",
"onmousedown",
"onmouseup",
"onmouseover",
"onmousemove",
"onmouseout",
"onfocus",
"onblur",
"onkeypress",
"onkeydown",
"onkeyup",
"onsubmit",
"onreset",
"onselect",
"onchange"];
and then I get all the elementsByTagName and want to check for their attribute:
var getAttrs = function() {
var i = 0,
j,
all = document.getElementsByTagName('*'),
max = all.length,
eventsLen = attr.length;
for (; i < max; i++) {
console.log('iterating through objects');
for (j = 0; j < eventsLen; j++) {
if (all[i].hasAttribute(attr[j])) {
console.log('found an instance of an intrinsec event', attr[j]);
}
}
}
};
This isn't working and I'm not getting any of the attributes I wanted to find.
Additionally, I'd like to find all attributes within all tags that use javascript: (such as in <a href="javascript:void(0)">) Any idea how I could add that to the function's logic?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要获取具有任一属性的所有元素,可以使用以下代码:
如果要选择与多个属性匹配的所有元素,请使用:
有关详细信息,请参阅 MDN:
document.querySelectorAll
。如果您需要更灵活的选择器,请查看:MDN:选择器
If you want to get all elements which have either attribute, the following code can be used:
If you want to select all elements which match multiple attributes, use:
For more information, see MDN:
document.querySelectorAll
.If you need more flexible selectors, have a look at: MDN: Selectors
更改:
至:
因为它也可以是属性,而不是属性。
Change:
To:
As it can also be a property and as opposed to an attribute.
这就是我要做的:
然后调用该函数将这些属性记录到控制台中:
现场演示: http://jsfiddle.net/F5AEy/
This is how I would do it:
and then just call that function to log those attribute into the console:
Live demo: http://jsfiddle.net/F5AEy/