JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<button>
Apply Bullet Point to Selected Text
</button>
<p contenteditable="true">
Text Text
</p>
<div>
Bullet point will not be applied to this sentence.
</div>
<br>
<p contenteditable="true">
Text Text
</p>
<div>
Bullet point will not be applied to this sentence.
</div>
JavaScript
$('button').on("click", function(e) {
var selected = getSelectedText();
var range = selected.getRangeAt(0);
if (selected.toString().length > 0) {
if ($(selected.anchorNode.parentNode).attr('contenteditable')) {
var newNode = document.createElement("li");
range.surroundContents(newNode);
}
}
selected.removeAllRanges();
});
function getSelectedText() {
var selectedText = '';
if (window.getSelection) {
selectedText = window.getSelection();
} else if (document.getSelection) {
selectedText = document.getSelection();
} else if (document.selection) {
// For IE prior to 9 as it does not support document.getSelection().
selectedText = document.selection.createRange().text;
} else return;
return selectedText;
}