KnockoutJS - Attr Binding


This binding allows you to dynamically assign HTML elements attribute using ViewModel property. For example, you can set src attribute for an image, title attribute for HTML page, or a href for a link in the tag based on values in ViewModel.


attr: <binding-object>


  • JavaScript object should be passed as a parameter in which the property name refers to attribute name and values refer to the desired values to be passed to DOM element.

  • Multiple attributes can also be assigned at once. Suppose you want to assign a title and href a value, then binding will look like the following −

<a data-bind = "attr: { href: courseUrl, title: courseTitle}">

courseUrl and courseTitle variables will have the desired values in ViewModel.

  • If the ViewModel property is an observable value, then attribute is assigned depending on the new updated parameter value. If it is not an observable value, then attribute is assigned only once for the first time.


Let us take a look at the following example which demonstrates the use of Attr binding.

<!DOCTYPE html>
      <title>KnockoutJS attribute binding</title>
      <script src = "" 
         type = "text/javascript"></script>
      <a data-bind = "attr: { href: courseUrl}">
         Click here for free online tutorials and courses.

      <script type = "text/javascript">
         function AppViewModel() {
            this.courseUrl = ("");
         var vm = new AppViewModel();


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

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

  • Open this HTML file in a browser.

  • The courseUrl will assign the value to href attribute in HTML DOM element.