問題描述
請注意 .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
、dir
、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中的所有元素屬性?
這篇關于如何獲取 DOM 元素上所有可能的有效屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!