Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the text of a span on click?

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.

like image 558
MrVimes Avatar asked Jul 12 '12 11:07

MrVimes


People also ask

How do I select text inside a span?

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.

Can we click on span in selenium?

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.

How do I change text in span?

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.

Can we make span clickable?

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.


1 Answers

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();     } }); 
like image 50
Eugene Manuilov Avatar answered Sep 25 '22 18:09

Eugene Manuilov