innerHTML用法及错误:无法设置未定义或null引用的属性“innerHTML”解决

在使用ActionCable时,

app/assets/javascripts/channels/calladdresses.coffee:

App.calladdress = App.cable.subscriptions.create "CalladdressChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    console.log(data)
    document.getElementById("app").innerHTML = data.title;

提示在chrome控制台 innerHTML is null 报告❌。

这是因为此时DOM还没有加载完成。

解决方法:

使用:

    document.addEventListener "turbolinks:load", ->
      document.getElementById("app").innerHTML = data.title;

传统做法是window.onload = function {} .

原文地址:https://www.cnblogs.com/chentianwei/p/9935543.html