【问题标题】:Get all IDL attributes for an HTML Element获取 HTML 元素的所有 IDL 属性
【发布时间】:2021-04-17 23:26:53
【问题描述】:

我知道可以像这样在标准 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" ]

我在一个世界(Salesforce Lightning Web 组件)中工作,IDL attributes(即您可以通过点符号访问的那些)并不总是公开为运行时的内容属性。例如,对于以下模板:

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

如您所见,我可以通过点符号访问labelvalue 等属性,但不能通过Element.attributes

我正在寻找的是一种内省元素上所有 IDL 属性的方法,用于测试目的。

【问题讨论】:

    标签: javascript attributes jsdom idl


    【解决方案1】:

    它们存在于原型上,因此您可以检查原型的 JS 属性:

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

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 2011-10-11
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多