I've been trying to get the selected value's label (not the value itself) in select2 widget, and copy it to clipboard using clipboardjs, but failed.
To reproduce this easily, please visit https://select2.org/getting-started/basic-usage and select 'Alaska' in the select2 example.
And from inspecting the element, i can see the element holding the selected value 'Alaska' in:
<span class="select2-selection__rendered" id="select2-zhjr-container" role="textbox" aria-readonly="true" title="Alaska">Alaska</span>
So i tried selection using this code, modified from clipboard.js source, to simulate selecting the text value through selection:
element = document.querySelector('#select2-zhjr-container')
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
selectedText = selection.toString();
console.log('selectedText: ' + selection)
And it turns out the selectedText is empty.
How to get the selectedText value correctly, so that it can be copied to clipboard using clipboardjs ?
Yes i could get the label text too using DOM, but then it's not copiable into clipboard. The label text has to be selected programmatically then copied into clipboard.
The selection and getting that selected text programmatically is what fails.
Thank you.