2

TLDR:

see: http://codepen.io/andrew-luhring/pen/Dkned for full example.

I have no idea why uncommenting the lines commented out below will produce the error: "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist."

(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);
})();

Essentially what I'm trying to do is take a text that is inserted into the dom as a text node, and replace it with a formatted version.

A snippet of the html looks like this:

<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>
Andrew Luhring
  • 1,762
  • 1
  • 16
  • 37
  • It does seem a little strange, you're iterating over elements, and setting the text of them all to the same variable, `pretext`, which now only holds the text of the last element? Then you're passing it all of to a function that is not in the above code `prettyfyText`, and god knows what that is returning, but it's probably DOM nodes, as you're getting an error when trying to use the return value of that function to set a selected text range ? – adeneo Jan 27 '14 at 00:28
  • The code was a bit long for me to post all of it considering that I'm only asking about the one error; the codepen has comments in the js that explain exactly whats going on – Andrew Luhring Jan 27 '14 at 00:31
  • and @adeneo it definitely is a hack, but I can't think of a different way to go about it without using jQuery. – Andrew Luhring Jan 27 '14 at 00:33
  • 1
    Wow. This simply crashes Opera. – Bergi Feb 08 '14 at 20:53
  • @Bergi lol really? does it give you a reason? is it the website that crashes opera or is it something about my code? – Andrew Luhring Feb 08 '14 at 21:13
  • No reason, unfortunately. But it seems be your code indeed, I can access other user accounts and "pens" without problems. Therefore: Always put the whole code on StackOverflow :-) What does `prettyfyText` return? Do you expect a difference between `result` and `resultArr` (I don't get the reason you used two arrays)? – Bergi Feb 08 '14 at 21:33
  • @Bergi Was trying to make it look less overwhelming. But yeah. It's all here now. If you feel like critiquing the code while you're at it, by all means. Could use some feedback about whether I'm being efficient and object oriented 'correctly'. – Andrew Luhring Feb 09 '14 at 00:25
  • Thank you. I don't see any object orientation in your code, but I don't think you'd need it. – Bergi Feb 09 '14 at 14:14
  • @Bergi yeah, I realized that this morning. I got a version of it working without the surroundcontent but it's kind of a hack: – Andrew Luhring Feb 10 '14 at 01:11
  • @Andrew: You better [write an answer yourself](http://stackoverflow.com/help/self-answer) instead of trying to squeeze your solution into a comment :-) – Bergi Feb 10 '14 at 01:13
  • Oh, but your answer actually answered the question, I just got by with a hack. just trying to give credit where it's due (to you :-) thanks dude! ). Hacks: [codepen](http://codepen.io/andrew-luhring/pen/Ilyjm) or [jsfiddle](http://jsfiddle.net/Luhring/3q99b/) – Andrew Luhring Feb 10 '14 at 01:26

1 Answers1

1

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()

You're confusing strings with Text nodes. setStart does require a DOM node as its arguments, but result[i] (and therefore resultArr[i]) is a plain string. Also, the surroundContents method requires an arguments as well.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375