How can I add an attribute to every `p` element in quilljs?

2k Views Asked by At

How can I add an attribute to every Block element in quilljs?

I know that I can extend a Block, but is it possible to add an attribute even when pressing "Enter" on the keyboard?

let Block = Quill.import('blots/block');

class ParaBlot extends Block {
   static create(value) {
      let node = super.create();
      return node;
   }
}
1

There are 1 best solutions below

1
On

To add an attribute like style or class to every Block element,

We could extend the default block blot element from the parchment lib,

Just like you are already doing, we import the Block Blot element and we extend the create(...) method to edit the node's attributes using the setAttribute function.

Here i'll be adding a border and a customBlock class for example.

Finnaly we override the default BlockBlot with ours

const BlockBlot = Quill.import('blots/block');

class CustomBlockBlot extends BlockBlot {
    static create(value) {
        const node = super.create(value);
        node.setAttribute('style', 'border: 1px solid lightgrey');
        node.setAttribute('class', 'customBlock');
        return node;
    }
}
Quill.register('formats/block', CustomBlockBlot);

Here is a demo https://codepen.io

This code block has to run before the target Quill instance is created with new Quill(...)

We should also consider that it isn't able to change formatting dynamically although i believe we could backup the Delta and create a fresh new Quill instance with these new defaults.

Another good post about this implement-custom-editor-for-quill-blot