How to get the ordinal of the current editor field from JavaScript?

Anki used to set something like id=f0 on the field divs. Currently, there doesn’t seem to be an obvious way to get the ordinal given a field’s shadow root obtained using document.activeElement.shadowRoot, for example.

2 Likes

It may not be an obvious way, but you can get the ordinal number of the field containing the shadow dom that has focus by iterating over the fields (the array of EditorFieldAPI), as follows:

(Typescript)

async function getFieldOrdinal(target: Element): Promise<number | null> {
    let fieldOrdinal: number | null = null;
    const fields = require("anki/NoteEditor").instances[0].fields;
    for (const [index, fieldApi] of fields.entries()) {
        const field: HTMLElement = await fieldApi.element;
        if (field.contains(target)) {
            fieldOrdinal = index;
            break;
        }
    }
    return fieldOrdinal;
}

getFieldOrdinal(document.activeElement?.shadowRoot?.host!).then((ord) =>
    console.log(`ord: ${ord}`)
);

2 Likes

I had something like this in mind, but couldn’t figure out how to do it. Thanks!

1 Like