Tobias Reich
Tobias Reich

Reputation: 2034

Get all elements of type in CKEditor 5

My editor contains custom elements, created like this:

this.editor.model.change( writer => {
    const id = `a${ Math.random().toString().replace('.', '') }`;

    const autocomplete = writer.createElement( 'autocomplete', { 'data-id': id );

    this.editor.model.insertContent( autocomplete );
} );

I want to get all 'autocomplete' elements at a later time in my plugin so I can read their content (they're editable elements).

Is there something like querySelectorAll('autocomplete') for the model of the editor?

Upvotes: 1

Views: 1600

Answers (1)

Tobias Reich
Tobias Reich

Reputation: 2034

It's possible using range.getWalker.

const findNodes = function(writer, type, root) {
    const nodes = [];
    const range = writer.createRangeIn( root );

    for ( const value of range.getWalker({ ignoreElementEnd: true }) ) {
        const node = value.item;

        if ( node.is( type ) ) {
            nodes.push(node);
        }
    }

    return nodes;
};

this.editor.model.change( writer => {
    const autocompletes = findNodes(writer, 'autocomplete', this.editor.model.document.getRoot());
} );

Upvotes: 4

Related Questions