WYSIWYG rich content editor. Part 2. Check if bold

The aim of these pages is to explain how to create a HTML rich content editor. The goal is to explain step by step how to build the editor.

This part explains how to detect if the current selection is in bold. In fact, it could work with any tag (<i>, <strike>, <span>...) but we'll focus on the <b> tag since this is the first we'll implement.

This part is necessary to create a bold button, because when the button is cliked we need to know if the current selection is already in bold or not. At the end of this section we'll get a (non working yet) bold button that will become blue if the current selection is in bold or not:

Create the button

First, create a bold button:

<button id="btn-bold"><b>B</b></button>

Add the CSS to set the button blue when the active class is added:

#btn-bold.active { color:blue; }

JavaScript

This is the tricky part. There is a queryCommandState() that automaticaly check if the current selection has a certain property. But we will not use it since this feature is obsolete.

Instead, we'll write our own detection function:

// Check if the current selection
function isSelectionInTag(tag)
{
    // Get the current node
    let currentNode = window.getSelection().focusNode;
    // While the node is not the editor division
    while (currentNode.id !== 'editor')
    {
        // Check if the node is the requested tag
        if (currentNode.tagName === tag) return true;
        // Move up in the tree
        currentNode = currentNode.parentNode;       
    }
    return false;
}

First, we get the current selection node:

let currentNode = window.getSelection().focusNode;

You can use either of then according to your expected behavior.

We'll then move up in the DOM tree until we

while (currentNode.id !== 'editor')
{
    // Check if the node is the requested tag
    if (currentNode.tagName === tag) return true;
    // Move up in the tree
    currentNode = currentNode.parentNode;       
}
return false; 

When the selection changes, we just have to check if the selection is in bold or not to update the button color:

if (isSelectionInTag('B')) btnBold.classList.add('active'); else btnBold.classList.remove('active');

Result

Try to click or select a normal and a bold part of the editor content. The bold button should become blue or not:

See also


Last update : 03/23/2020