4

What would be an approach to select text within span tag when considering browser compatibility? Example, I have:

jQuery().html('<p>Hello world <span>lorem ipsum</span> my good friend!');

I want the lorem ipsum part to be cursor selected.

I have this code which selects text:

function SelectText(element) {
    var doc = document
        , text = doc.getElementById(element)
        , range, selection
    ;    
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
Community
  • 1
  • 1
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

2

you mean like this?

 var i = 0; 
function SelectText(element) {
    var doc = document
        , text = doc.querySelectorAll(element)
        , range, selection
    ;
 
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text[i]);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text[i]);
        selection.removeAllRanges();
        selection.addRange(range);
    }
  i++;
   if ( i === text.length ) i = 0;
}

document.onclick = function(e) {    
    if (e.target.className === 'click') {
        SelectText('span');
    }
};
<div>Hello world <span>lorem ipsum</span> my good friend!</div>
<div>Hello world <span>lorem ipsum</span> my good friend!</div>
<p class="click">Click me!</p>

if you just need to select one tag element you can use querySelector instead of querySelectorAll


here's an example with .html()

$(function() {
   $('body').html('<p>Hello world <span>lorem ipsum</span> my good friend!');
  })

function SelectText(element) {
    var doc = document
        , text = doc.querySelector(element)
        , range, selection
    ;
 
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
  
}

window.onload = function() {    
 
        SelectText('span');
    
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
maioman
  • 18,154
  • 4
  • 36
  • 42
  • 1
    This is exactly what I mean, however, I want to output the text using .html() and have the text wrapped in selected on pageload, not on click. – Henrik Petterson Feb 19 '16 at 23:07
  • Thank you for the update, although the .html() is added via ajax (after pageload). Sorry I did not clarify this properly. Can you adjust your code to output .html() via ajax and have text within span tag selected? I will bounty this with 50 points when eligible for the effort. Thanks! It's been a headache all day. – Henrik Petterson Feb 19 '16 at 23:31
  • the point is to call the function right after the content has been added, if you have problems open up a new question – maioman Feb 19 '16 at 23:51
  • ...lorem ipsum my old friend. I've come to talk with you again. Because a vision softly creeping hello world while I was sleeping... – Sean Kendle Jan 30 '18 at 19:00
0

HTML CODE

<input type="text" name="firstName" value="Enter your name..." />

JS CODE

//SELECT TEXT RANGE
$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
$('input[name=firstName]').focus().selectRange(5,10);

Click Here For Permanent link to jsfiddle

//SELECT TEXT RANGE
$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
$('input[name=firstName]').focus().selectRange(5,10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="firstName" value="Enter your name..." />
Heemanshu Bhalla
  • 3,603
  • 1
  • 27
  • 53
  • @Henrik Petterson This Can Help you For Cursor Selection – Heemanshu Bhalla Feb 19 '16 at 23:01
  • [`setSelectionRange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) is valid only in an `` or ` – OfirD Apr 29 '20 at 13:36