简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM