4

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();
}; 
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
m.wallgren
  • 79
  • 1
  • 4
  • oh i failed to post the html code: – m.wallgren Nov 05 '15 at 14:52
  • Varför?

    Usp:

    Skriv här
    – m.wallgren Nov 05 '15 at 14:52
  • 1
    Don't you mean JavaScript? Entirely different from Java. Also there's a stray `/` in your ``. [Probable duplicate](http://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse) – Kenney Nov 05 '15 at 14:54
  • ye im sorry, i meant javascript – m.wallgren Nov 05 '15 at 14:57
  • Also there are another mistake in your code `document.getElementsByClassName('text1')[0]` will be correct. Note the plural in getElement**s**, it returns a bundle of DOM elements, so we catch the first with `[0]`. `this.select()` it's not correct also, because `this` is not referencing anywhere, you are not inside an scope – Marcos Pérez Gude Nov 05 '15 at 15:02

1 Answers1

11

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);
};
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
  • 1
    Yes, thanks a lot! works just fine, i dont know where the stray came from.. well now it works! thansk again! – m.wallgren Nov 05 '15 at 15:05
  • @m.wallgren No problem!! Happy to help. If you felt this answer was sufficient for you I would not mind if you accepted it as the answer. trying to earn rep for privileges! =] – AtheistP3ace Nov 05 '15 at 15:07
  • I am using this now. Works great. Thanks! FYI, alter it a tad to accept a span `selectSpanText(span)` – Ronnie Royston Mar 06 '17 at 21:27