你的意思是这样的吗?
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');
}
};
Click me!
,如果你只需要选择一个标签元素,你可以使用querySelector代替querySelectorAll
这里以.html()的一个例子
$(function() {
$('body').html('
Hello world lorem ipsum 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');
};