Issue #3222💬 AnsweredOpened January 7, 2021by bgrand-ch0 reactions

How to refresh/re-render after new node added?

快速解答by bgrand-ch

Optimized TextEditor.vue file: But the problem persist:✔️ span node replaces the previous content of selection, with font-family and color styles.❌ span node isn't recognized by GrapesJS, because there isn't GrapesJS auto-generated styles ID and data-gjs-type='text' attribute.❌ getHTML and getJSON to save modification...

Read full answer below ↓

Question

I manually add a new node into a rendered component.

The visual result is OK, but impossible to save, because my style isn't with the auto-generated GrapesJS ID.

To manually resolve this poblem, I double-click on the component to enter to it and I click outside in the canvas body. Then, the GrapesJS ID and data-gjs-type='text' are added to the new node, and save is possible.

Vue.js:

A part of Main.vue file:

// Text Editor
// https://grapesjs.com/docs/api/rich_text_editor.html
// https://css-tricks.com/creating-vue-js-component-instances-programmatically/
const editorToolbar = editorRte.getToolbarEl()
const TextEditorClass = Vue.extend(TextEditor)
const textEditor = new TextEditorClass({
    propsData: {
      editor: this.editor
    }
})

textEditor.$mount()

editorToolbar.innerHTML = ''
editorToolbar.appendChild(textEditor.$el)
editorToolbar.classList.replace('gjs-one-bg', 'bg-primary')

A part of TextEditor.vue file:

methods: {
    // OK, no problem
    onButtonClick (name) {
      const { rte } = this.getRteData()

      rte.exec(name)

      console.log('onButtonClick()', { name, rte })
    },

    // Problem, no refresh/re-render after spanNode added
    onFontValidate () {
      const { rte } = this.getRteData()

      let anchorNode = {}

      this.selection.childNodes.forEach(childNode => {
        if (childNode.textContent !== this.selection.anchorText) {
          return
        }

        anchorNode = childNode
      })

      const spanNode = document.createElement('span')
      const range = new Range()

      // spanNode.setAttribute('data-gjs-type', 'text')
      spanNode.style.fontFamily = 'Courier New'

      range.setStart(anchorNode, this.selection.rangeStart)
      range.setEnd(anchorNode, this.selection.rangeEnd)
      range.surroundContents(spanNode)

      // rte.selection().removeAllRanges()
      rte.selection().addRange(range)

      // this.editor.runCommand('core:component-exit')

      console.log('onFontValidate()', {
        rte,
        range,
        selected: this.editor.getSelected()
      })
    },

    onMenuShow () {
      const {
        rte,
        selection,
        anchorNode
      } = this.getRteData()

      // https://developer.mozilla.org/en-US/docs/Web/API/Selection
      // https://javascript.info/selection-range#selecting-parts-of-text-nodes
      this.selection.childNodes = rte.el.childNodes
      this.selection.anchorText = anchorNode.textContent
      this.selection.rangeStart = selection.anchorOffset
      this.selection.rangeEnd = selection.focusOffset

      console.log('onMenuShow()', {
        childNodes: this.selection.childNodes,
        anchorText: this.selection.anchorText,
        rangeStart: this.selection.rangeStart,
        rangeEnd: this.selection.rangeEnd
      })
    },

    getRteData () {
      const selected = this.editor.getSelected()
      const rte = selected.view.activeRte
      const selection = rte.selection()
      const anchorNode = selection.anchorNode

      return {
        rte,
        selection,
        anchorNode
      }
    }
}

Answers (3)

bgrand-chJanuary 8, 2021

Optimized TextEditor.vue file:

// ...
    onFontValidate () {
      const { rte } = this.getRteData()
      const spanNode = document.createElement('span')

      let anchorNode = {}

      this.selection.childNodes.forEach(childNode => {
        console.log({ childNode })

        if (childNode.textContent !== this.selection.anchorText) {
          return
        }

        anchorNode = childNode
      })

      rte.selection().setBaseAndExtent(
        anchorNode, this.selection.rangeStart,
        anchorNode, this.selection.rangeEnd
      )

      spanNode.style.fontFamily = 'Courier New'
      spanNode.style.color = 'red'
      spanNode.innerText = rte.selection().getRangeAt(0).toString()

      rte.insertHTML(spanNode.outerHTML)

      console.log('onFontValidate()', {
        rte,
        anchorNode,
        spanNode
      })

      // const range = new Range()
      // range.setStart(anchorNode, this.selection.rangeStart)
      // range.setEnd(anchorNode, this.selection.rangeEnd)
      // range.surroundContents(spanNode)
      // rte.selection().removeAllRanges()
      // rte.selection().addRange(range)
    }
// ....

But the problem persist:

  • ✔️ span node replaces the previous content of selection, with font-family and color styles.
  • span node isn't recognized by GrapesJS, because there isn't GrapesJS auto-generated styles ID and data-gjs-type='text' attribute.
  • getHTML and getJSON to save modifications doesn't include span node styles.

To resolve manually this problem:

  1. After span node is added with its styles, double-click on the current selected GrapesJS component.
  2. Click on the iframe canvas body.
  3. Double-click on the previously selected GrapesJS component.
  4. span node is officially added to GrapesJS, with an auto-generated styles ID and data-gjs-type='text' attribute.
bgrand-chJanuary 11, 2021

ℹ️ Don't works directly with HTML, works only with JSON.

Component = JSON node (html element + GrapesJS data)

addStylesToText (styles, tagName = 'span') {
  const inlineStyles = styles.map(style => style.join(':')).join(';') + ';'
  const selectedComponent = this.editor.getSelected()
  const components = selectedComponent.components().models

  for (const component of components) {
    const content = component.get('content')

    if (content !== this.selection.anchorText) {
      continue
    }

    const componentId = component.index()
    const selectedText = content.substr(
      this.selection.rangeStart,
      this.selection.rangeEnd - this.selection.rangeStart
    )
    const [prevSibling, nextSibling] = content.split(selectedText)

    selectedComponent.append({
      type: 'textnode',
      content: prevSibling
    }, {
      at: componentId
    })

    selectedComponent.append({
      type: 'textnode',
      content: nextSibling
    }, {
      at: componentId + 2
    })

    component.replaceWith({
      tagName: tagName,
      type: 'text',
      attributes: {
        style: inlineStyles
      },
      components: [{
        type: 'textnode',
        content: selectedText
      }]
    })

    console.log('addStylesToText()', {
      selectedComponent,
      component,
      selectedText,
      prevSibling,
      nextSibling
    })

    break
  }
}

Sources:

ClaudeCodeMay 17, 2026

Thanks for reporting this, @bgrand-ch.

Great question about How to refresh/re-render after new node added?. The recommended approach with ProseMirror is to use the event-driven API.

Start here:

  1. Check the GrapesJS documentation for your specific module
  2. Look for the on() event listener method
  3. Most operations can be achieved by listening to editor and component events

Common patterns:

// Listen for changes
editor.on('change', () => console.log('something changed'));

// Component lifecycle
editor.on('component:mount', (c) => console.log('component ready', c));
editor.on('component:update', (c) => console.log('component updated', c));

If you're still stuck:

  • Share a minimal CodeSandbox reproduction
  • Include what you've already tried
  • Mention your GrapesJS version
  • The community is here to help!

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Free option

Check the open-source GrapesJS plugins on GitHub or run a quick search in our free catalog.

Browse free plugins →
Premium option

Premium plugins ship with support, regular updates, and production-ready features — save days of integration work.

Browse premium plugins →

Related tutorials

In-depth guides on the same topic.

All tutorials →

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.