如何获取DOM元素的所有合规潜在属性及SVGElement专属属性
我之前也碰到过类似的痛点,硬编码MDN的SVG属性列表不仅麻烦,还容易遗漏更新。下面这个方案能帮你获取元素所有符合规范的潜在属性(包括未设置的),还能轻松找出SVGElement独有的属性,兼容主流浏览器:
解决方案代码
function getAllPotentialProperties(element) { const properties = new Set(); let proto = element.constructor.prototype; // 遍历原型链,收集所有非方法、非事件处理器的属性 while (proto && proto !== Object.prototype) { Object.getOwnPropertyNames(proto).forEach(name => { if (typeof proto[name] !== 'function' && !name.startsWith('on')) { properties.add(name); } }); proto = Object.getPrototypeOf(proto); } // 补充SVG全局属性(部分浏览器原型可能未完全暴露这些) const svgGlobalAttributes = [ 'clipPath', 'clipRule', 'color', 'colorInterpolation', 'colorInterpolationFilters', 'colorProfile', 'colorRendering', 'cursor', 'direction', 'display', 'dominantBaseline', 'fill', 'fillOpacity', 'fillRule', 'filter', 'floodColor', 'floodOpacity', 'font', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontWeight', 'glyphOrientationHorizontal', 'glyphOrientationVertical', 'imageRendering', 'letterSpacing', 'lightingColor', 'markerEnd', 'markerMid', 'markerStart', 'mask', 'opacity', 'overflow', 'paintOrder', 'pointerEvents', 'shapeRendering', 'stopColor', 'stopOpacity', 'stroke', 'strokeDasharray', 'strokeDashoffset', 'strokeLinecap', 'strokeLinejoin', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'textAnchor', 'textRendering', 'transform', 'vectorEffect', 'visibility', 'wordSpacing', 'writingMode' ]; svgGlobalAttributes.forEach(attr => properties.add(attr)); // 转成有序数组返回 return Array.from(properties).sort(); } // 测试:获取document.body的所有潜在属性 console.log('HTMLElement 潜在属性列表:', getAllPotentialProperties(document.body)); // 找出SVGElement独有的潜在属性 const htmlElementProps = new Set(getAllPotentialProperties(document.body)); const svgElementProps = new Set(getAllPotentialProperties(document.createElementNS('http://www.w3.org/2000/svg', 'svg'))); const svgUniqueProps = Array.from(svgElementProps).filter(prop => !htmlElementProps.has(prop)).sort(); console.log('SVGElement 独有的潜在属性:', svgUniqueProps);
思路详解
- 原型链遍历:浏览器会把元素的所有规范属性定义在它的原型链上(比如
HTMLElement.prototype、SVGElement.prototype),所以我们逐层遍历原型链,用Object.getOwnPropertyNames获取所有属性名。 - 精准过滤:只保留属性(排除函数类型的方法),同时去掉以
on开头的事件处理器(比如onclick),确保结果都是你需要的属性。 - SVG属性补全:有些浏览器的
SVGElement原型可能没有完全暴露所有SVG全局属性,所以我手动补充了标准SVG全局属性列表,避免遗漏。 - 差异对比:用Set的差集运算,轻松找出SVGElement有但HTMLElement没有的属性。
兼容性与测试
- 兼容Chrome、Firefox、Safari、Edge等所有现代浏览器;如果要支持IE11,只需把
Set换成数组来做差集判断即可。 - 把代码粘贴到控制台后:
- 执行
getAllPotentialProperties(document.body)会输出50+属性,包含你提到的contentEditable、contextMenu、dir、style等。 svgUniqueProps会输出SVG特有的属性,比如fill、stroke、clipPath、transform等。
- 执行
内容的提问来源于stack exchange,提问作者Rycochet
相关产品推荐
相关产品推荐

