JSFiddle - React, Tailwind, and code Playground
by Imri Paloja
HTML
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
/>
<div class="main container">
<button onclick="toggleBold()">Bold / Unbold</button>
<div id="editor" contenteditable="true">
<h1>Notes From Underground By Fyodor Dostoyevsky</h1>
<p>A man living alone in St. Petersburg writes memoirs describing his alienation from modern society.</p>
<hr>
<p>44,336 words (2 hours 42 minutes) with a reading ease of 69.92 (fairly easy)</p>
<p>Translated by Constance Garnett.</p>
<p>Fiction</p>
<hr>
<p>Notes from Underground is a fictional collection of memoirs written by a civil servant living alone in
St. Petersburg. The man is never named and is generally referred to as the Underground Man. The
“underground” in the book refers to the narrator’s isolation, which he described in chapter 11 as
“listening through a crack under the floor.”</p>
<p>It is considered to be one of the first existentialist novels. With this book, Dostoevsky challenged the
ideologies of his time, like nihilism and utopianism. The Underground Man shows how idealized
rationality in utopias is inherently flawed, because it doesn’t account for the irrational side of
humanity.</p>
<p>This novel has had a big impact on many different works of literature and philosophy. It has influenced
writers like Franz Kafka and Friedrich Nietzsche. A similar character is also found in Martin Scorsese’s
Taxi Driver.</p>
<p>Notes from Underground was published in 1864 as the first four issues of Epoch, a Russian magazine by
Fyodor and Mikhail Dostoevsky. Presented here is Constance Garnett’s translation from 1918.</p>
</div>
</div>
CSS
#editor {
background: #eeeeee;
border: 1px solid #cccccc;
border-radius: 5px;
padding: 20px 30px;
margin: 20px 3px;
}
JavaScript
function toggleBold() {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
// Ensure selection is inside the editor
const editor = document.getElementById("editor");
if (!editor.contains(range.commonAncestorContainer)) return;
const parent = range.commonAncestorContainer.parentElement;
// If already bold → unwrap
if (parent && parent.tagName === "STRONG") {
const textNode = document.createTextNode(parent.textContent);
parent.replaceWith(textNode);
selection.removeAllRanges();
const newRange = document.createRange();
newRange.selectNodeContents(textNode);
selection.addRange(newRange);
}
// Else → wrap in <strong>
else {
const strong = document.createElement("strong");
range.surroundContents(strong);
selection.removeAllRanges();
const newRange = document.createRange();
newRange.selectNodeContents(strong);
selection.addRange(newRange);
}
}