JSFiddle - React, Tailwind, and code Playground
HTML
<div id="first" class="specialDiv" style="background:yellow">DIV1: First some <b>bold text</b> for you to select
<br>
<button>Reply</button>
</div>
<br>
<div id="second" class="specialDiv" style="background:green">DIV2: Second some <i>test text for you to</i> select
<br>
<button>Reply</button>
</div>
<br>
<div id="third" class="specialDiv" style="background:lightblue">DIV3: <span style="color:pink">Third some</span> test text for you to select
<br>
<button>Reply</button>
</div>
<br>
<i>(there could be more similar divs on a page)</i>
JavaScript
function getSelectedText() {
if (window.getSelection) {
return "" + window.getSelection();
} else if (document.selection && document.selection.type == "Text") {
return document.selection.createRange().text;
}
return "";
}
function getSelectionContainerElement() {
var container = null;
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
container = sel.getRangeAt(0).commonAncestorContainer;
if (container.nodeType != 1) {
container = container.parentNode;
}
}
} else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
container = document.selection.createRange().parentElement();
}
return container;
}
var hasClass = (typeof document.documentElement.classList == "undefined") ?
function(el, clss) {
return el.className && new RegExp("(^|\\s)" +
clss + "(\\s|$)").test(el.className);
} :
function(el, clss) {
return el.classList.contains(clss);
};
function getSelfOrAncestorWithClass(node, theClass) {
while (node) {
if (hasClass(node, theClass)) {
return node;
} else {
node = node.parentNode;
}
}
return null;
}
function doSomethingWithSelectedText() {
//"remove quoteButton"
var buttons = document.getElementsByClassName('quoteButton');
if (buttons.length){
var button = buttons[0];
button.innerHTML = 'Reply';
var classArr = button.className.split(' ');
classArr.splice(classArr.indexOf('quoteButton'), 1);
button.className = classArr.join(' ');
}
//check if new quoteButton should be labeled
if (getSelectedText() !== "") {
var containerWithSpecialClass = getSelfOrAncestorWithClass(getSelectionContainerElement(), 'specialDiv');
if (containerWithSpecialClass) {
...