简体   繁体   English

获取 HTML 元素的所有 IDL 属性

[英]Get all IDL attributes for an HTML Element

I know it's possible to get all content attributes on aa standard HTMLElement like this:我知道可以像这样在标准HTMLElement上获取所有内容属性

<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 (ie those you can access via dot notation) aren't always exposed as content attributes at runtime.我在一个世界(Salesforce Lightning Web 组件)工作,其中IDL 属性(即您可以通过点符号访问的那些)在运行时并不总是作为内容属性公开。 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 .如您所见,我可以通过点符号访问诸如labelvalue之类的属性,但不能通过Element.attributes访问。

What I'm looking for is a way to introspect all IDL attributes on an element, for testing purposes.我正在寻找的是一种内省元素上所有 IDL 属性的方法,用于测试目的。

They exist on the prototype, so you can examine the prototype's JS properties:它们存在于原型中,因此您可以检查原型的 JS 属性:

 const getKeys = obj => obj? Object.keys(obj).concat(getKeys(Object.getPrototypeOf(obj))): []; console.log( getKeys(document.querySelector('input')) );
 <input>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM