Why am I getting a "Cannot read property 'nodeType' of null" error with Knockout JS?

47,574

Solution 1

If you set up your code like this, it'll work.

<body>
<p>Number1:<input data-bind="value:n1"></p>
<p>Number2:<input data-bind="value:n2"></p>
<p>Number3:<input data-bind="value:n3"></p>
<script src="knockout.js"></script>
<script>

function ViewModel() {  
   var self = this;  
   self.n1 = ko.observable(10);  
   self.n2 = ko.observable(10);  
   self.n3 = ko.observable(10);
}  

ko.applyBindings(new ViewModel());  `

</script>
</body>

Solution 2

If you want to keep your <script> at the top of the page, you can use jQuery's ready() function to delay the initialization until the page has loaded.

$(document).ready(function() {
    ko.applyBindings(new ViewModel());
});

Solution 3

I think ko.applyBindings(obj); should be write under view model.

<!DOCTYPE html>
<html>
<head>
    <title>KO Examples</title>
    <script type='text/javascript' src='knockout-3.1.0.js'></script>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript'>
        var  obj = {
            first_name : 'Gazal Irish'
        };


    </script>

</head>
<body>
<div>
    <p>My name : <span data-bind="text: first_name"></span>
<p> 
</div>
<script type="text/javascript">

    ko.applyBindings(obj);
</script>

</body>
</html>
Share:
47,574
Prasath K
Author by

Prasath K

Skills : HTML5 JavaScript jQuery d3.js SharePoint 2013 Angular.js

Updated on July 07, 2020

Comments

  • Prasath K
    Prasath K almost 4 years

    Today is the first day for me in Knockout . Got struck with it . Below is my first sample code using knockout.js and it shows an error .

    Cannot read property 'nodeType' of null

    Here is my script:`

       function ViewModel()  
       {  
         var self = this;  
         self.n1 = ko.observable(10);  
         self.n2 = ko.observable(10);  
         self.n3 = ko.observable(10);  
       }  
       ko.applyBindings(new ViewModel());  `
    

    Here is my html:

    <body>
    <p>Number1:<input data-bind="value:n1"></input></p>
    <p>Number2:<input data-bind="value:n2"></input></p>
    <p>Number3:<input data-bind="value:n3"></input></p>
    </body>
    

    I want to know the reason for the above error and how to overcome it...