molily: Absoluten Index einer Node finden

Beitrag lesen

inwiefern die falsche Funktion?

var nodeIndex;  
function getChildNodeIndex(parent, node) {  
  nodeIndex++;  
  for(var i = 0; i < parent.childNodes.length; i++)  
    if(parent.childNodes[i] == node || getDomChilds(parent.childNodes[i], node))  
      return true;  
  return false;  
}

Du musst hier getChildNodeIndex aufrufen, nicht getDomChilds. Da hast du wohl zwei Beispiele vermischt.

Mein (überarbeiteter) Testcode:

<!DOCTYPE html>  
<html>  
<head>  
<script>  
[code lang=javascript]function doit () {  
   function getNodeIndex (needle) {  
      var nodeIndex = -1;  
      walk(document.body);  
      return nodeIndex;  
  
      function walk (parent) {  
         nodeIndex++;  
         console.debug(nodeIndex, parent.nodeType == 1 ? parent.nodeName : parent.nodeValue);  
         var childNodes = parent.childNodes;  
         for (var i = 0, l = childNodes.length; i < l; i++) {  
            var node = childNodes[i];  
            if (needle == node || walk(node)) {  
               console.debug('found needle');  
               return true;  
            }  
         }  
      }  
   }  
   var selection = window.getSelection();  
   var anchorNodeIndex = getNodeIndex(selection.anchorNode);  
   var focusNodeIndex = getNodeIndex(selection.focusNode);  
   alert(anchorNodeIndex + ' bis ' + focusNodeIndex);  
}

</script>
</head>
<body>
<p>aaaaa</p>
<p>bbbbb</p>
<p>ccccc</p>
<p>ddddd</p>
<p>eeeee</p>
<input type="button" value="do it" onclick="doit()">
</body>
</html>[/code]

Markieren und Button klicken. Funktioniert hervorragend in Chrome 12.

Wobei der nodeIndex bei dieser Umsetzung immer für alle Kinder gilt, d.h. wenn ich innerhalb des aaaaa-Textknoten markiere, so bekomme ich für Anfang und Ende der Auswahl den nodeIndex des p-Elternelements.

Mathias