Get all IDL attributes for an HTML Element

北慕城南 提交于 2021-01-29 17:21:44

问题


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" ]

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>

I get the following behavior:

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" ]

As you can see, I can access properties like label and value via dot notation, but not via Element.attributes.

What I'm looking for is a way to introspect all IDL attributes on an element, for testing purposes.


回答1:


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>


来源:https://stackoverflow.com/questions/65693648/get-all-idl-attributes-for-an-html-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!