KnockoutJS - HTML Binding


Advertisements

HTML binding causes the associated DOM element to display the HTML specified by the parameter. This is very useful if you want to generate HTML markup dynamically.

Syntax

html: <binding-value>

Parameters

  • KnockoutJS sets DOM element's content to the parameter value provided. This functionality is also available in JQuery. If JQuery is not available, then KO is used to achieve this.

  • If the parameter is observable, then elements value is updated as and when the underlying observable is changed. Element is processed only once, if no observable is used.

Example

Let us take a look ath the following example which demonstrates the use of html binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Html binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <p><span data-bind="html: welcomeMessgae "></span></p>
      
      <script>
         function AppViewModel() {
            this.welcomeMessgae = ko.observable();
            this.welcomeMessgae ("<strong>Welcome to TutorialsPoint !!! For free online tutorials and courses click <a href = 'https://tutorialspoint.com/'>here</a>.</strong>");
         }
         
         ko.applyBindings(new AppViewModel());
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in html-bind.htm file.

  • Open this HTML file in a browser.

knockoutjs_declarative_bindings.htm
Advertisements