Add data-bind dynamically in knockoutjs

Sami C.
1 min readApr 10, 2020

For the rare species that are still doing knockoutJS😅 Ever wanted to add a data-bind attribute to a dynamically generated element? I’ll show you how.

Add data-bind and reapply the binding:

Once your element has been placed in your HTML you can execute the following snippet to add the data-bind attribute:

document.querySelector('.myClass').setAttribute('data-bind', 'visible: false');ko.applyBindings(Model, document.querySelector('.myClass'));

By applying the binding to the element with the new data-bind attribute knockoutjs will execute the value of the data-bind attribute.

Hopefully this helps some of you out there!

Enjoy!

--

--