Every time getRangeAt creates the Same Range?
Namit Singh
Posted on October 10, 2020
I am creating Range in the loop but every time getRangeAt creates the same Range. why is it so?
My scenario is very simple I have getting positions of words from the database and on page load highlight words or substrings at those positions but every time on the first word all tags added. Like if 4 times loop runs then 4 span tags will add only on the first matching word.
var r = document.createRange();
var s = window.getSelection();
// alert(s);
console.log(s);
// var abc = window.getSelection();
var pos = 0;
var start,end;
var range = [];
function dig(el){
$(el).contents().each(function(i,e){
if (e.nodeType==1){
// not a textnode
dig(e);
}
else
{
if (pos
if (pos+e.length>=start){
range.setStart(e, start-pos);
}
}
if (pos<end){
if (pos+e.length>=end){
range.setEnd(e, end-pos);
}
}
pos = pos+e.length;
}
});
}
function highlight(element,st,en){
range = document.createRange();
start = st;
end = en;
dig(element);
s.addRange(range);
}
$(document).ready(function(){
var x;
var url = window.location.pathname;
var urlid = url.substring(url.lastIndexOf('/') + 1);
$.ajax({
type:'GET',
url:'/check-words',
data:{urlid:urlid},
success:function(data){
for (let [index,x] of data.entries())
{
var jsondata = x + '';
var nameArr = jsondata.split(',');
console.log('when x is', x);
console.log('nameArr is', nameArr);
var a = nameArr[0];
var b = nameArr[1];
highlight($('.main-detail-content'), a, b);
var ra = s.getRangeAt(0); // this line always create same range even positions are different evry time loop runs.
var newNode = document.createElement("em");
newNode.appendChild(ra.extractContents());
ra.insertNode(newNode);
}
}
})
});
Posted on October 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.