javascript - 这是怎么出现 "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist. "错误的?

标签 javascript dom textnode

简单描述:

见: http://codepen.io/andrew-luhring/pen/Dkned 完整的例子。

我不知道为什么取消注释下面注释掉的行会产生错误: “未捕获的 NotFoundError:试图在不存在的上下文中引用节点。”

(function() {
  //====================================================
  //    globals
  //    
  //
  //
    var div = document.createElement('div');
    var bd = document.body;
    var range = document.createRange();
    div.id = 'swagyo';


  //====================================================
  //    surroundTxt
  //    takes a range object and surrounds it with (withThis)
  //
  //
  //
    function surroundTxt(rangeObj, withThis) {
        rangeObj.surroundContents(withThis);
    }


  //====================================================
  //    prettyfyText
  //    takes a string, splits it at the regex, prepends keepthis, appends addThis
  //    Returns an array of the newly created substrings.
  //
  //
    function prettyfyText(str, regExp, addThis, keepthis) {
    var result;
    if (str.search(regExp) != -1) {
        var splitted = str.split(regExp),
            arr = [];
        if (keepthis) {
            for (var i = 0; i < splitted.length; i++) {
                result = keepthis + '' + splitted[i] + ' ' + addThis;
                arr.push(result);
            }
        } else {
            for (var i = 0; i < splitted.length; i++) {
                result = splitted[i] + ' ' + addThis;
                arr.push(result);
            }
        }

    } else {
        result = 'fail  \n ' + str
        console.log(result);
        return (false);
    }
    return arr;
}


  //====================================================
  //    constructTxt
  //    takes the text that immediately follows div#info and passes it to surroundTxt.
  //
  //
  //
    function constructTxt() {
        var txt = info.nextSibling;
        range.setStart(txt, 0);
        range.setEnd(txt, txt.length);
        setTimeout(surroundTxt(range, div), 10);
    }


  //    grabPreText
  //    takes the text within the pre element (pretext)
  //    sends (pretext) to prettyfyText - names the returned array (result)
  //
  //
  //
  //
  //====================================================
  //====================================================
  //            THIS IS WHERE THE ERRORS ARE
  //                        v
  //                        v
  //====================================================
  //====================================================
    function grabPreText() {
        var pre = info.getElementsByTagName('pre'),
            parent = info,
            pretext,
            result,
            content,
            resultArr = [],
            newrange = document.createRange(),
            re = new RegExp(('Applications'), 'g'),
            newline = '\n',
            keepthis = 'applications',
            p = document.createElement('p'),
            newdiv = document.createElement('div');

        for (var i = 0; i < pre.length; i++) {
            pretext = pre[i].innerText;
        }
        result = prettyfyText(pretext, re, newline, keepthis);

        for (var i = 0; i < result.length; i++) {
            var current = result[i];

            resultArr.push(current);
            console.log(resultArr[i].length);



  //uncommenting 113- 116 the following will cause the error:
  /* 
      newrange.setStart(resultArr[i], 0);
      newrange.setEnd(resultArr[i], resultArr[i].length );
      console.log(newrange);
      newrange.surroundContents()
  */

            content = document.createTextNode(result[i]);
            newdiv.appendChild(content);

    }


    if (result) {
      console.log('\n \n ========= \n' + newdiv.innerText);
      console.log("if newdiv is: " + newdiv);
      console.log("and if parent is: " + parent);
      console.log("and if pre is: "+ pre);
      console.log("then why does parent.replaceChild(newdiv, pre) produce the error:" + "\n An attempt was made to reference a Node in a context where it does not exist. ?");
  //        parent.replaceChild(newdiv, pre);
      info.appendChild(newdiv);
      var space = document.createTextNode(newline + ' ' + newline);
      info.appendChild(space);

    }
  }


  //====================================================    
  //    totallyReady (the equivilant of document ready.)
  //    
  //
  //
    function totallyReady() {
      var info = document.getElementById('info');
      grabPreText();
      constructTxt();
    }
    setTimeout(totallyReady, 10);
})();

本质上,我要做的是将插入到 dom 中的文本作为文本节点,并将其替换为格式化版本。

一段 html 如下所示:

<html>
<body>
    <div id="info">
        <pre>
    /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -DF_CPU=16000000L -DARDUINO=100 -I/Users/worker_bee/Documents/Arduino/ardu -I/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino -I/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/include/avr -I/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/variants/standard -mmcu=atmega328p applet/ardu.cpp -o applet/ardu.o
        </pre>
    </div>applet/ardu.cpp:2: error: expected unqualified-id before '/' token applet/ardu.cpp: In function 'void setup()': applet/ardu.cpp:14: error: 'outputPin' was not declared in this scope applet/ardu.cpp: In function 'void printStuff()': applet/ardu.cpp:36: error: 'outputPin' was not declared in this scope applet/ardu.cpp:37: error: 'writeStuff' was not declared in this scope applet/ardu.cpp: In function 'void writeStuff()': applet/ardu.cpp:50: error: 'outputPin' was not declared in this scope make: *** [applet/ardu.o] Error 1 
</body>
</html>

最佳答案

Why will uncommenting this cause the error An attempt was made to reference a Node in a context where it does not exist?

newrange = document.createRange()
newrange.setStart(resultArr[i], 0);
newrange.setEnd(resultArr[i], resultArr[i].length);
newrange.surroundContents()

您将字符串与文本节点混淆了。 setStart确实需要一个 DOM 节点作为其参数,但是 result[i](因此 resultArr[i])是一个纯字符串。此外,surroundContents method也需要参数。

关于javascript - 这是怎么出现 "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist. "错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21371154/

相关文章:

javascript - 如何在 AngularJS 工厂中使用来自 API 的数据

javascript - this.getElementById 不是函数

javascript - getBBox() 对比 getBoundingClientRect() 对比 getClientRects()

dom - 是否有任何重要的浏览器缺少 HTML 文档的 document.documentElement?

javascript - D3.js:enter().append()后的属性未设置

javascript - 显示大文本(部分彩色)

JavaScript - 将元素节点 append 到文本节点父级

javascript - scrolltop with if less than 不起作用

javascript - 从 CSV 文件返回值 (jQuery/Javascript)

javascript - 将textNode内容转换为字符串