Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text inside <span> onClick

Im using a text span field and want to select the text inside on click, im not using jQuery, so i wonder if i can do it with java functions?

here is the code:

<div id="container">
   <h2> Varför?</h2>
   <h3> Usp: </h3>
   <div>
      <span contenteditable="true" onClick="toggle11();"/ class="text1">
         Skrivhär
      </span>
   </div>
</div>

And my function:

function toggle11() {
    var i = document.getElementByClassName("text1")
    this.select();
}; 
like image 946
m.wallgren Avatar asked Dec 25 '22 12:12

m.wallgren


1 Answers

So there were a few things wrong. First as someone pointed out there was a stray slash in html. Second its getElementsByClassName. Here is a fiddle. Is this what you wanted?

Fiddle: http://jsfiddle.net/yb7rt2dL/

function toggle11() {
    var el = document.getElementsByClassName("text1")[0];
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
};
like image 133
AtheistP3ace Avatar answered Dec 27 '22 03:12

AtheistP3ace