m.wallgren
m.wallgren

Reputation: 79

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();
}; 

Upvotes: 4

Views: 6735

Answers (1)

AtheistP3ace
AtheistP3ace

Reputation: 9691

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);
};

Upvotes: 11

Related Questions