I am looking for a way to select the text inside a span using jquery when the text is clicked on.
For example in the html snippet below, I want the text "\apples\oranges\pears" to become selected when it is clicked on.
<p>Fruit <span class="unc_path">\\apples\oranges\pears</span></p>
I've tried implementing this myself to no avail.
To select the specific Span you need a id to be provided to that span. Else you need to loop through the list of all available span to get it. hm.. this is only alternative way to identify the element being clicked on.
We can select the text of a span on click with Selenium webdriver. To identify the element with span tag, we have to first identify it with any of the locators like xpath, css, class name or tagname. After identification of the element, we can perform the click operation on it with the help of the click method.
Use the textContent property to change the text of a span element, e.g. span. textContent = 'Replacement text' . The textContent property will set the text of the span to the provided string, replacing any of the existing content.
Just add an id to the span element, and then in a js file attach an event to that id when you click it, and when that happens trigger the funcionality.
It could be implemented with native JavaScript. A working demonstration on jsFiddle. Your code could be like this:
$('.unc_path').click(function (){ var range, selection; if (window.getSelection && document.createRange) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents(this); selection.removeAllRanges(); selection.addRange(range); } else if (document.selection && document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(this); range.select(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With