How can I get the selected string when using a toolbar button in Gutenberg?


I have added a button to the Block Editor. Currently it adds a <span class="lqdnotes-blank-it"> before the selected text and </span> after it like so:

<span class="lqdnotes-blank-it">Selected Text.</span>

Here is the current code:

(function ( wp ) {
    var lqdNotesButton = function( props ) {
        return wp.element.createElement(
            wp.blockEditor.RichTextToolbarButton, {
                icon: 'editor-code',
                title: 'Blank It',
                onClick: function () {
                    props.onChange( wp.richText.toggleFormat(
                        { type: 'lqdnotes/blankit' }

        'lqdnotes/blankit', {
            title: 'Blank It',
            tagName: 'span',
            className: 'lqdnotes-blank-it',
            edit: lqdNotesButton,
} )( window.wp );

I’d like to change how this functions. Instead of adding a class around it I’d like it to replace the selected text with an input textbox. The desired result would look like:

<input type="text" class="lqdnotes-blanked" id="FirstFifteenCharsOfSelectedTextUniqueID">

Thus one might have post content like:

“The American Civil War commenced in 1861 and concluded in 1865.”

If the individual toggled on the button on 1861 and 1865 the output might look like:

“The American Civil War commenced in <input type="text" class="lqdnotes-blanked" id="1861lqd0001"> and concluded in <input type="text" class="lqdnotes-blanked" id="1865lqd0002">.”

What I’ve been unable to figure out thus far is how I get the value of the selected text and how I return it as part of the input’s id.

, davemackey 2 years 2019-10-31T15:08:51-05:00 0 Answers 67 views 0

Leave an answer