JSFiddle - React, Tailwind, and code Playground
HTML
<div id="outline">
<p>some text</p>
<p>some more text</p>
<p>some more text</p>
</div>
<div id="result"></div>
JavaScript
$(document).ready(function () {
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
$('#outline').on('click', function () {
var text = getSelectedText();
var parent = getSelectionParentElement();
$(parent).attr('id', 'id' + Math.floor((Math.random() * 1000) + 1));
$('#result').html('Setting selected text parent ID to be: ' + $(parent).attr('id'));
});
});