0

I have a dynamically-generated unordered list of < li> elements laid out by a knockout view model, and I'd like to make just one of those < li> elements have a class or CSS property when the view loads. I'd like to avoid using jQuery and keep it as purely-knockout as possible.

viewModel.headers = [
            { title: 'Item 1', sortKey: 'item1', asc: true, active: false },
            { title: 'Item 2', sortKey: 'item2', asc: false, active: true },
            { title: 'Item 3', sortKey: 'item3', asc: true, active: false},
            { title: 'Item 4', sortKey: 'item4', asc: true, active: false }
        ];

Here's the HTML:

    <ul data-bind="foreach: headers">
        <li data-bind="text: title"></li>
    </ul>

I've tried using the pseudo CSS selector nth-child(2) to select the second li item in that list and apply styling, but of course that unordered list doesn't exist when the CSS is considered by the browser. Similar issue with jQuery, although I could still use jQuery/Js to interact with dynamically-created elements (like here Event binding on dynamically created elements?), but I'm almost certain there's a quick and clean way to do it with Knockout. I've looked at Knockout's "style" and "css" bindings, but I can't directly add a property to the HTML for the unordered list as I am using foreach to generate the li elements when the page is loaded from the view model...

Community
  • 1
  • 1
jspinella
  • 2,013
  • 3
  • 25
  • 39

2 Answers2

2

All you need to do is to bind css in your element. if active property in your object is true it gets active class
HTML:

 <ul data-bind="foreach: headers">
        <li data-bind="text: title,css:{'active':active}"></li>
  </ul>

Example :http://jsfiddle.net/GSvnh/5133/

Matin Kajabadi
  • 3,414
  • 1
  • 17
  • 21
1

You can use a binding that sets the CSS class using Knockout. You need to have a way of determining which one to highlight, of course.

I added an observable called selected in this Fiddle

I then added a css binding:

<ul data-bind="foreach: headers">
  <li data-bind="text: title, css: $root.GetClass(title)"></li>
</ul>

and a function thus:

  self.GetClass = function(title) {
    return self.selected() == title ? "selected" : "";
  }

Hope this helps.

Quango
  • 12,338
  • 6
  • 48
  • 83