I create paragraph in tiptap 2, how to add a class to this paragraph

221 Views Asked by At

below is my tiptap code which creates paragraph

<script>
  this.editor.commands.insertContent({
      type: 'paragraph',
      HTMLAttributes: {
          class: 'created-paragraph',
      },
      content: [{ type: 'text', text }],
  });
</script>

i created a paragraph like this, but "HTMLAttributes" is not working, how to add a class in other way? i cant figure it out :(

i hope guys u can help me

2

There are 2 best solutions below

1
On

you can use the addClass method to add a class to a node.

this.editor.chain().focus().insertContent({
    type: 'paragraph',
    content: [
        {
            type: 'text',
            text
        },
    ],
}).run();

this.editor.chain().focus().addClass('created-paragraph').run();

The chain method is used for chaining commands. Each call to a method like focus, insertContent, or addClass returns a new chain instance, and the run method is used to execute the chain of commands.

0
On

yo, i found the way how u can create ur custom

import { mergeAttributes, Node } from '@tiptap/core';
import Paragraph from '@tiptap/extension-paragraph';

const CustomParagraph = Node.create({
  name: 'customParagraph',
  group: 'block',
  content: 'text*',
  parseHTML() {
    return [{ tag: 'p.custom-paragraph' }];
  },
  renderHTML({ HTMLAttributes }) {
    return ['p', mergeAttributes(HTMLAttributes, { class: '' }), 0];
  },
  addAttributes() {
    return {
      class: {
        default: null,
      },
    };
  },
});

export default CustomParagraph;

and then u can use this customParagraph in ur code, just import it

this.editor.commands.insertContent({
  type: 'customParagraph',
  attrs: {
    class: paragraphClass,
  },
  content: [{ type: 'text', text }],
});