admin管理员组

文章数量:1320614

I'm stuck trying to acplish what I'd imagine is a very simple task in TipTap 2.0. I'm trying to add a class to a selected paragraph. The code I'm trying is below:

this.editor.chain().focus().updateAttributes('paragraph', {class:'lead'});

I want this to be editable per paragraph. I don't want all paragraphs to have the same class added.

I'm stuck trying to acplish what I'd imagine is a very simple task in TipTap 2.0. I'm trying to add a class to a selected paragraph. The code I'm trying is below:

this.editor.chain().focus().updateAttributes('paragraph', {class:'lead'});

I want this to be editable per paragraph. I don't want all paragraphs to have the same class added.

Share Improve this question asked Feb 27, 2023 at 14:09 alexmcfarlanealexmcfarlane 1,1482 gold badges16 silver badges37 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

So after some further investigation, I have found a solution for this. My initial assumption was incorrect. I thought that you use updateAttributes to directly add a class to the paragraph. But you need to extend Paragraph with your own 'class' attribute, then you can amend the HTML using renderHTML.

const CustomParagraph = Paragraph.extend({
            addAttributes() {
                return {
                    class: {
                        default: null,
                        // Take the attribute values
                        renderHTML: attributes => {
                            // … and return an object with HTML attributes.
                            return {
                                class: `${attributes.class}`,
                            }
                        },
                    },
                }
            },
        })

this.editor = new Editor({
            element: this.tiptapEditorTarget,
            extensions: [
                CustomParagraph,
            ],
        });

this.editor.mands.updateAttributes('paragraph', {class:'lead'});

Alternatively, if you'd like decorate only the focused paragraph, you can use the existing "focus" extension, with minimal setup: https://tiptap.dev/docs/editor/extensions/functionality/focus

  // extensions configuration
  focus.configure({
    className: "focused",
  }),
/** CSS file */
  p.focused {
    color: black
  }

本文标签: javascriptAdd a class to a paragraph node in TipTapStack Overflow