There are a lot of articles published to stackoverflow and in other websites which are relevant to the way of selecting text of ONE element in order to be available for copy.
But I have not found a function which can SELECT AND HIGHLIGHT the text of ALL similar elements in an HTML document. For example, to select the text from all h2 titles.
I tried to modify the function from this thread which selects one element.
SELECTING ONE ELEMENT FUNCTION
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
Here is the modified version of the above function which performs the selection of all similar elements.
$.fn.selectTextAll = function() {
var doc = document,
numElem = this.length,
elements = this;
if(doc.body.createTextRange) {
for(i=0; i<numElem; i++) {
var range = document.body.createTextRange();
range.moveToElementText(elements[i]);
range.select();
}
}
else if(window.getSelection) {
var selection = window.getSelection();
selection.removeAllRanges();
for(i=0; i<numElem; i++) {
var range = document.createRange();
range.selectNodeContents(elements[i]);
selection.addRange(range);
}
}
};
The problem is that the above function is working properly in Firefox but in no other browser, Chrome, Safari, Opera, IE+9.
In order to confirm this, you can open this fiddle in all browsers. It is working only in Firefox.
Can anyone give a solution to this?
Thank you for your time