In Knockout js, there is one function called "afterRender" Use that to achieve expected output.
Magento 2.x Doc Link for afterRender binding notifies its subscriber when an associated element is inserted into the DOM.
Sometimes we want to run custom post-processing logic (after DOM ready) on the DOM elements generated by our templates.
For example,
if we're using a JavaScript widgets library such as jQuery UI and want
to intercept templates output so that we can run jQuery UI commands on
it to transform some of the rendered elements into date pickers,
sliders, or anything else.
Generally, the best way to perform such LOGIC's on DOM elements is to
write a custom binding,
but if we really just want to access the raw
DOM elements emitted by a template, we can use afterRender
.
Pass a function reference (either a function literal, or give the name of a function on your view model), and Knockout will invoke it immediately after rendering or re-rendering our template.
For example,
<div data-bind='template: { name: "personTemplate",
data: myData,
afterRender: applyOurLogicAfterDOMReady }'> </div>
and define a corresponding function on your view model (i.e., the object that contains myData):
viewModel.applyOurLogicAfterDOMReady = function(elements) {
// "elements" is an array of DOM nodes just rendered by the template
// You can add custom post-processing logic here
}
If we're using foreach
, Knockout will invoke afterRender
callback for each item added to our observable array.