如何获取DOM元素上所有可能的有效属性
请注意 .attributes
只获取当前属性,这不是这个问题的内容。
Please note that .attributes
only gets the current attributes, which is not what this question is about.
我想要一种方法来获得 所有 DOM元素的属性。不仅是现在的那些,还有将来可能的那些。
I want a way to get all the attributes of a DOM element. Not just the ones that are on it now, but the ones that are possible in the future too.
具体的用例是找到 SVGElement 不在 HTMLElement
中 - 在MDN上有一个列表( SVG属性参考),但由于显而易见的原因,硬编码并不是一个好主意。
The specific use case is to find the potential attributes in an SVGElement
that aren't in an HTMLElement
- there's a list on MDN (SVG Attribute reference), but, for obvious reasons, hardcoding is not a good idea.
我最初的想法是迭代每个实例的原型链并比较两个列表(使用事件处理程序的基本过滤),但这实际上并没有给出潜在的svg属性。
My initial thought was to iterate through the prototype chain of an instance of each and compare the two lists (with basic filtering for event handlers), but this doesn't actually give the potential svg attributes.
编辑
- 重要提示 - 粘贴您的答案代码进入此页面的控制台,并使用
document.body
作为目标应显示超过50个属性的列表,包括contentEditable
,contextMenu
,d ir
,style
等。 - 这也需要跨浏览器工作。
- IMPORTANT NOTE - pasting your answer code into the console on this page and using
document.body
as a target should show a list of over 50 attributes, including things likecontentEditable
,contextMenu
,dir
,style
, etc. - This also needs to work cross-browser.
这样的事情可能就是你想要的吗?
Could something like this be what you're looking for?
看起来像DOM元素对象存储所有可能属性的空键。你可以循环这些键并将它们存储在一个数组中,然后从那里使用类似的东西来过滤掉继承的属性吗?
It looks like a DOM element object stores empty keys for all possible attributes. Could you loop over these keys and store them in an array, then from there use something similar to filter out inherited attributes?
HTML
<svg id="blah"></svg>
Javascript
const blah = document.getElementById('blah')
let possibleKeys = []
for (let key in blah) {
possibleKeys.push(key)
}
这是 JSBin示例 ...看起来它会生成所有可能属性的列表,但需要进行一些过滤。
Here's a JSBin example ... it looks like it produces a list of all possible attributes but it would need some filtering.
另见此主题。
如何列出JS中的所有元素属性?