question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Another "Uncaught TypeError: Cannot set property 'textContent' of null"

See original GitHub issue

This appears to be the same as #177

I can’t give a JSFiddle as this is tied to a back end framework.

In any case, surely we should get something that indicates where the problem originates.

moon.js:865 Uncaught TypeError: Cannot set property 'textContent' of null
    at diff (moon.js:865)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at diff (moon.js:926)
    at Moon.patch (moon.js:1942)
diff @ moon.js:865
diff @ moon.js:926
diff @ moon.js:926
diff @ moon.js:926
diff @ moon.js:926
diff @ moon.js:926
diff @ moon.js:926
diff @ moon.js:926
diff @ moon.js:926
Moon.patch @ moon.js:1942
Moon.build @ moon.js:1977
(anonymous) @ moon.js:191
setTimeout (async)
queueBuild @ moon.js:190
Moon.set @ moon.js:1770
(anonymous) @ index.js:162
self.emit @ uibuilderfe.js:434
self.set @ uibuilderfe.js:219
(anonymous) @ uibuilderfe.js:282
r.emit @ index.js:133
r.onevent @ socket.js:270
r.onpacket @ socket.js:228
(anonymous) @ index.js:21
r.emit @ index.js:133
r.ondecoded @ manager.js:345
(anonymous) @ index.js:21
r.emit @ index.js:133
s.add @ index.js:241
r.ondata @ manager.js:335
(anonymous) @ index.js:21
r.emit @ index.js:133
r.onPacket @ socket.js:456
(anonymous) @ socket.js:273
r.emit @ index.js:133
r.onPacket @ transport.js:145
r.onData @ transport.js:137
ws.onmessage @ websocket.js:147

For what it may be worth, the index.js is:

/*global document,window,Moon,uibuilder */
// @ts-ignore
/*
  Copyright (c) 2017 Julian Knight (Totally Information)

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
/**
 * This is based on the default, template Front-End JavaScript for uibuilder
 * It has been changed to remove JQuery and use MoonJS instead.
 * 
 * uibuilderfe.js (or uibuilderfe.min.js) exposes the following global object.
 * Note that you can use webpack or similar to bundle uibuilder with your own code.
 * 
   * uibuilder: The main global object containing the following...
   *   External Methods:
     *   .onChange(property, callbackFn) - listen for changes to property and execute callback when it changes
     *   .get(property)        - Get any available property
     *   .set(property, value) - Set any available property (can't overwrite internal properties)
     *   .msg                  - Shortcut to get the latest value of msg. Equivalent to uibuilder.get('msg')
     *   .send(msg)            - Shortcut to send a msg back to Node-RED manually
     *   .sendCtrl(msg)        - Shortcut to send a control msg back to Node-RED manually (@since v0.4.8)
     *   .debug(true/false)    - Turn on/off debugging
     *   .uiDebug(type,msg)    - Utility function: Send debug msg to console (type=[log,info,warn,error,dir])
     *   .me()                 - Returns the self object if debugging otherwise just the current version string
     *   .autoSendReady(true/false) - If true, sends "ready for content" ctrl msg on window.load
     *                   If false, you will need to do uibuilder.sendCtrl({'type':'ready for content'}) manually
     *                   (e.g. in an app.mounted event)  @since v0.4.8a
   *
   *   All properties can be read using the .get method
   *   New properties can be added via .set method as long as the property name does not clash with anything internal.
   *   All properties (including custom) can have change events associated with them by using the .onChange method
   *
   *   Externally settable properties using special methods only
     *   .autoSendReady - see .autoSendReady method
     *   .debug         - see .debug method, also see 'server connected' control msg from server
   *
   *   Externally settable properties via the .set method
     *   .allowScript   - Allow incoming msg to contain msg.script with JavaScript that will be automatically executed
     *   .allowStyle    - Allow incoming msg to contain msg.style with CSS that will be automatically executed
     *   .removeScript  - Delete msg.code after inserting to DOM if it exists on incoming msg
     *   .removeStyle   - Delete msg.style after inserting to DOM if it exists on incoming msg
   *
   *   Externally read only properties (may be changed internally)
     *   .msg           - Copy of the last msg sent from Node-RED over Socket.IO
     *   .sentMsg       - Copy of the last msg sent by us to Node-RED (both data and control)
     *   .ctrlMsg       - Copy of the last control msg received by us from Node-RED (Types: ['shutdown','server connected'])
     *   .msgsReceived  - How many standard messages have we received
     *   .msgsSent      - How many messages have we sent
     *   .msgsSentCtrl  - How many control messages have we sent
     *   .msgsCtrl      - How many control messages have we received
     *   .ioConnected   - Is Socket.IO connected right now? (true/false)
     *   ---- You are not likely to need any of these, they are for internal use ----
     *   .version       - check the current version of the uibuilder code
     *   .ioChannels    - List of the channel names in use [uiBuilderControl, uiBuilderClient, uiBuilder]
     *   .retryMs       - starting retry ms period for manual socket reconnections workaround
     *   .retryFactor   - starting delay factor for subsequent reconnect attempts
     *   .ioNamespace   - Get the namespace from the current URL
     *   .ioPath        - make sure client uses Socket.IO version from the uibuilder module (using path)
     *   .ioTransport   - ['polling', 'websocket']
     *   .timerid       - internal use only
     *   .events        - list of registered events
 */
"use strict";

// Attach a Moon instance to html element with id "app"
const app1 = new Moon({
    el: "#app",
    data: {
        startMsg    : "Moon has started, waiting for messages",
        feVersion   : '',
        counterBtn  : 0,
        socketConnectedState: false,
        msgsReceived: 0,
        msgsControl : 0,
        msgsSent    : 0,
        msgRecvd    : '[Nothing]',
        msgSent     : '[Nothing]',
        msgCtrl     : '[Nothing]',
        inputText   : '',
        updates     : {}, // devId: {updated,}
        homie       : {} // devId: {updated,}
    }, // --- End of data --- //
    computed: {
        hLastRcvd: {
            get: function() {
                const msgRecvd = this.get('msgRecvd')
                if (typeof msgRecvd === 'string') return 'Last Message Received = ' + msgRecvd
                else return 'Last Message Received = ' + this.callMethod('syntaxHighlight', [msgRecvd])
            }
        },
        hLastSent: {
            get: function() {
                const msgSent = this.get('msgSent')
                if (typeof msgSent === 'string') return 'Last Message Sent = ' + msgSent
                else return 'Last Message Sent = ' + this.callMethod('syntaxHighlight', [msgSent])
            }
        },
        hMsgCtrl: {
            get: function() {
                const msgCtrl = this.get('msgCtrl')
                if (typeof msgCtrl === 'string') return 'Last Message Sent = ' + msgCtrl
                //else return 'Last Message Sent = ' + this.callMethod('syntaxHighlight', [msgCtrl])
                else return 'Last Message Sent = ' + JSON.stringify(msgCtrl)
            }
        },
    }, // --- End of computed --- //
    methods: {
        // Increment the button counter
        increment: function() {
            // Increment the count by one
            this.set('counterBtn', this.get('counterBtn') + 1)
            let topic = (this.get('msgRecvd')).topic || 'uibuilder/moon'
            uibuilder.send( { 'topic': topic, 'payload': { 'type': 'counterBtn', 'btnCount': this.get('counterBtn'), 'message': this.get('inputText') } } )
        },
        // return formatted HTML version of JSON object
        syntaxHighlight: function(json) {
            json = JSON.stringify(json, undefined, 4)
            json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                var cls = 'number'
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'key'
                    } else {
                        cls = 'string'
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'boolean'
                } else if (/null/.test(match)) {
                    cls = 'null'
                }
                return '<span class="' + cls + '">' + match + '</span>'
            })
        } // --- End of syntaxHighlight --- //
    }, // --- End of methods --- //
    hooks: { // Available hooks: init,mounted,updated,destroyed
        
        mounted: function(){
            //console.debug('app mounted - setting up uibuilder watchers')

            var that = this

            that.set( 'feVersion', uibuilder.get('version'))

            // If msg changes - msg is updated when a standard msg is received from Node-RED over Socket.IO
            // Note that you can also listen for 'msgsReceived' as they are updated at the same time
            // but newVal relates to the attribute being listened to.
            uibuilder.onChange('msg', function(newVal){
                that.set( 'msgRecvd', newVal)

                /** If we receive an MQTT type msg with topic 'homie/<deviceId>/...
                 * NB: MoonJS <v1 if needing to set whole topic, use the form:
                 *     instance.set("updates[homie/devId]", val)
                 *     e.g. no inner quotes
                 */
                if ( newVal.hasOwnProperty('topic') ) {
                    let splitTopic = newVal.topic.split('/')
                    let devId = splitTopic[1]
                    if ( splitTopic[0] === 'homie' ) {
                        let homie = that.get('homie')
                        if ( !homie.hasOwnProperty(devId) ) {
                            homie[devId] = {'updated':null,'battery':null,'signal':null,'temperature':null,'humidity':null,'pressure':null,'light':null,'location':null,'online':'','count':0,'command':'','cmdUnit':''}
                            //homie[devId] = {'battery':null}
                        }
                        if ( splitTopic[3] === '$updated' ) {
                            homie[devId].updated = newVal.payload.replace('"','').replace('Z"','')
                        }
                        if ( splitTopic[3] === 'battery' ) {
                            homie[devId].battery = newVal.payload
                        }
                        if ( splitTopic[3] === 'signal' ) {
                            homie[devId].signal = newVal.payload
                        }
                        if ( splitTopic[3] === 'temperature' ) {
                            homie[devId].temperature = newVal.payload
                        }
                        if ( splitTopic[3] === 'humidity' ) {
                            homie[devId].humidity = newVal.payload
                        }
                        if ( splitTopic[3] === 'pressure' ) {
                            homie[devId].pressure = newVal.payload
                        }
                        if ( splitTopic[3] === 'light' ) {
                            homie[devId].light = newVal.payload
                        }
                        if ( splitTopic[3] === 'cmd' ) {
                            homie[devId].command = newVal.payload
                        }
                        if ( splitTopic[3] === 'unit' ) {
                            homie[devId].cmdUnit = ' (' + newVal.payload + ')'
                        }

                        if ( splitTopic[2] === '$location' ) {
                            homie[devId].location = newVal.payload
                        }
                        if ( splitTopic[2] === '$online' ) {
                            homie[devId].online = newVal.payload ? ' (Online)' : ' (Online)'
                        }
                        if ( splitTopic[2] === '$count' ) {
                            homie[devId].count = newVal.payload
                        }
                        //uibuilder.set('homie',homie)
                        that.set('homie', homie)
                    }
                }
            })
            // As noted, we could get the msg here too
            uibuilder.onChange('msgsReceived', function(newVal){
                //console.info('New msg sent FROM Node-RED over Socket.IO. Total Count: ', newVal)
                app1.set( 'msgsReceived', newVal)
            })


            // If a message is sent back to Node-RED
            uibuilder.onChange('sentMsg', function(newVal){
                //console.info('property sentMsg changed!', newVal)
                app1.set( 'msgSent', newVal)
            })
            uibuilder.onChange('msgsSent', function(newVal){
                //console.info('New msg sent TO Node-RED over Socket.IO. Total Count: ', newVal)
                app1.set('msgsSent', newVal )
            })


            // If we receive a control message from Node-RED
            uibuilder.onChange('ctrlMsg', function(newVal){
                console.info('msgCtrl received %o', newVal)
                app1.set( 'msgCtrl', newVal)
            })
            uibuilder.onChange('msgsCtrl', function(newVal){
                //console.info('New CONTROL msg sent FROM Node-RED over Socket.IO. Total Count: ', newVal)
                app1.set('msgsControl', newVal )
            })

            // If Socket.IO connects/disconnects
            uibuilder.onChange('ioConnected', function(newVal){
                //console.info('Socket.IO Connection Status Changed: ', newVal)
                app1.set('socketConnectedState', newVal )
            })

        } // --- End of mounted hook --- //
    } // --- End of hooks --- //
}) // --- End of app1 --- //

// EOF

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Marc-oOcommented, Jan 24, 2018

You rock, as usual. From now, a simple workaround could be using a “getter” : check if the variable exists, else return a space… (i used that…)

1reaction
TotallyInformationcommented, Dec 4, 2017

Thanks. I will give that a go as soon as I can. May be a few days though as I’m deep into a planning exercise in my day job just now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: Cannot set property 'textContent' of null [duplicate]
You have something that is calling this initially and getting a null value and then resolving later i think. So try this.
Read more >
app.js:6 Uncaught TypeError: Cannot set property 'textContent ...
I cannot find the error in the code that is causing the problem. ... app.js:6 Uncaught TypeError: Cannot set property 'textContent' of null...
Read more >
LWC Error: Cannot set property 'textContent' of null
Your text variable (the lightning-button ) is null because it's absent from the DOM. It's absent from the DOM because it's inside the ......
Read more >
"Cannot set property 'textContent' of null" when ... - GitHub
"Cannot set property 'textContent' of null" when creating PDFViewer #12320 ... Error: Uncaught (in promise): TypeError: Cannot set property ...
Read more >
Cant set property textContent of null - Sololearn
Hello, it happens me a lot here when I use a textContent or innerHTML property that I get an error saying uncaught typeError:...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found