Chapter 2. The Ins and Outs of Data Binding

Binding HTML Data

In Example 1-1, text was data-bound to a span tag. Like text, it’s quite common to data-bind content that contains HTML data.

In Example 2-1, the getName function is expanded to wrap the output of the name data binding with some HTML code.

HTML Versus Text Binding

HTML bindings work similarly to text with the exception that they render any HTML tags provided. If you were to use the text binding with HTML content, the HTML would be escaped, and the content would be displayed as text.

In Example 2-1, I update two things. First, the data-bind attribute is moved from the span tag to the h1 tag. Second, it is bound to the getName function, which has been updated to contain some HTML code.

Example 2-1. h1 tag with HTML binding
<!DOCTYPE html>
    <title>Data Binding with KnockoutJS</title>

    <h1 data-bind="html: getName()"></h1> 

    <script type='text/javascript' src='js/knockout-3.2.0.js'></script> 
        function ViewModel() { 

            var self = this; 

   = 'Steve Kennedy'; 

            self.getName = function() { 
                return 'Hello <em>' + + '</em>!'; 

        var viewModel = new ViewModel();

Running Example 2-1 would output a similar message to Example 1-1, with the exception that the name would be italicized because of the HTML tag around the output of the name property.

Binding HTML Attributes, CSS Classes, and CSS Styles

Knockout can bind almost ...

Get Knockout.js now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.