skip to Main Content

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

Answers


  1. You can add classes or styles to the content by extending the schema and creating your own node with the desired attributes.

    import { Node } from 'tiptap';
    
    export default class CustomParagraph extends Node {
      get name() {
        return 'customParagraph';
      }
    
      get defaultOptions() {
        return {
          class: 'created-paragraph',
        };
      }
    
      get schema() {
        return {
          attrs: {
            class: {
              default: this.options.class,
            },
          },
          content: 'inline*',
          group: 'block',
          draggable: false,
          parseDOM: [{
            tag: 'p.created-paragraph',
          }],
          toDOM: node => ['p', { class: node.attrs.class }, 0],
        };
      }
    }
    

    Usage in editor

    import { Editor } from 'tiptap';
    import CustomParagraph from './CustomParagraph';
    
    const editor = new Editor({
      content: '<p>Some text here</p>',
      extensions: [
        CustomParagraph,
      ],
    });
    

    When you use this.editor.commands.insertContent to insert a paragraph, you can use the custom node

    this.editor.commands.insertContent({
      type: 'customParagraph',
      content: [{ type: 'text', text }],
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search