Any way to get the ".indexOf()" string position of the start and end of a jQuery-selected element relative to the parent?
Example:
<ul><li>Coffee</li><li>Coffee</li><li>Coffee</li></ul>
After selecting the 2nd <li>
item via jquery, the function would return 15 (or 29 with an argument switch).
I am thinking about a verbose javascript workaround but it gets nasty and unreliable very fast. Also it might not work if there are other tag types or text mixed in between. Bad. Not to take seriously.
//http://stackoverflow.com/a/14482123
function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n-- && i++<L){
i= str.indexOf(pat, i);
}
return i;
}
function strpos(jelem, tag) {
var nth = jelem.index();
var contents = jelem.parent().text();
var pos = nthIndex(contents, tag, nth+1);
if (tag.indexOf('/') == 1) {
return pos+4; //because ending of '</li>' is +4 (very bad)
} else {
return pos;
}
}
strpos(jelem, '<li>'); //or '</li>' to return the ending position