获取HTML元素的所有IDL属性 [英] Get all IDL attributes for an HTML Element
问题描述
我知道可以像这样在标准 HTMLElement
上获取所有 content属性 :
I know it's possible to get all content attributes on a a standard HTMLElement
like this:
<input type="text" value="John" />
const input = document.querySelector("input");
const attrs = Array.from(input.attributes);
console.log(attrs.map(a => a.name + ': ' a.value)); // [ "type: text", "value: John" ]
我在一个世界(Salesforce Lightning Web Components)工作,其中
I'm working in a world (Salesforce Lightning Web Components) where IDL attributes (i.e. those you can access via dot notation) aren't always exposed as content attributes at runtime. For example, for the following template:
<lightning-input label="First Name" value="John" data-id="fname">
</lightning-input>
我得到以下行为:
const input = element.shadowRoot.querySelector("lightning-input");
// I can get all these IDL attributes via dot notation
console.log(input.label); // First Name
console.log(input.value); // John
console.log(input.dataset.id); // fname
const attrs = Array.from(input.attributes);
// But they don't all show up here
console.log(attrs.map(a => a.name + ': ' a.value)); // [ "data-id: fname" ]
如您所见,我可以通过点符号访问属性,例如 label
和 value
,但不能通过
As you can see, I can access properties like label
and value
via dot notation, but not via Element.attributes
.
我要寻找的是一种对元素上的所有IDL属性进行内省以进行测试的方法.
What I'm looking for is a way to introspect all IDL attributes on an element, for testing purposes.
推荐答案
它们存在于原型中,因此您可以检查原型的JS属性:
They exist on the prototype, so you can examine the prototype's JS properties:
const getKeys = obj => obj
? Object.keys(obj).concat(getKeys(Object.getPrototypeOf(obj)))
: [];
console.log(
getKeys(document.querySelector('input'))
);
<input>
这篇关于获取HTML元素的所有IDL属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!