JSFiddle - React, Tailwind, and code Playground
HTML
<div id="target">
<span>click to select all </span>
<span>text</span>
</div>
JavaScript
document.getElementById('target').addEventListener('click', function (event) {
console.log(event.target.innerHTML)
if (window.getSelection && document.createRange) { //Browser compatibility
sel = window.getSelection();
if(sel.toString() == ''){ //no text selection
window.setTimeout(function(){
range = document.createRange(); //range object
range.selectNodeContents(event.target); //sets Range
sel.removeAllRanges(); //remove all ranges from selection
sel.addRange(range);//add Range to a Selection.
},100);
}
}else if (document.selection) { //older ie
sel = document.selection.createRange();
if(sel.text == ''){ //no text selection
range = document.body.createTextRange();//Creates TextRange object
range.moveToElementText(el);//sets Range
range.select(); //make selection.
}
}
});