Search code examples
javascriptattributesjsdomidl

Get all IDL attributes for an HTML Element


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.


Solution

  • 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>