joe_coolish joe_coolish - 4 years ago 171
Javascript Question

Knockout.js get dom object associated with data

I'm working with knockout.js to build dynamic lists and I'm trying to figure out how I can get the DOM object associated with an object in my observable array. Specifically I want to get the jQuery for a row.


<ul data-bind="foreach: Item">
<li data-bind="events: {click: getDomObject}, text: 'text: ' + text">

in the
function, I would like to be able to get the specific
DOM object so that I can do some jQuery manipulation with it.

I've thought about adding an
member to the Item ViewModel and then add the id as the line item's html id and then select based on that, but I feel that there should be an easier way.

What is the proper way to reference the dynamic HTML generated by knockout.js?

Answer Source

Event handlers like click get passed two arguments. That is a) the item that this event belongs to - like the entry of an observable array that you're rendering with the foreach binding ("Item" in your case). And b) an event object, that provides you with more information about the actual event. This object contains the DOM element that got clicked on (key "target"):

getDomObject = function(item, event) {
    var $this = $(;
    // ...

Just a note: Don't mix knockout and native jQuery DOM manipulations - if you can achieve the same result with clever knockout bindings, I would recommend going with that.

And here is a simple demo:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download