I have h2 tag with data-bind text property to a model value and inside i have a span tag which is also a data-bind text property to a model value.
But span is getting replace when the model is binded, is there any way to append the html.
I have h2 tag with data-bind text property to a model value and inside i have a span tag which is also a data-bind text property to a model value.
But span is getting replace when the model is binded, is there any way to append the html.
Normally, you would want to change your HTML to work properly for this scenario. However, if that is not possible, then you could use a custom binding that inserts the span for you.
It would be like:
ko.bindingHandlers.insertText = {
init: function(element, valueAccessor) {
var span = document.createElement("span"),
firstChild = element.firstChild;
element.insertBefore(span, firstChild);
ko.applyBindingsToNode(span, { text: valueAccessor() });
}
};
Your current code will overwrite because the 'text' binding sets the innerText (or textContent) for that element, so your h2 text binding will overwrite any existing embedded html (such as your span).
You could do this:
<h2>
<span data-bind="text:firstName"></span>
<span data-bind="text:lastName "></span>
</h2>