5

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.

http://jsfiddle.net/WKnWr/1/

3 Answers 3

9

With the newest knockout you could use a virtual element for the h2 text, similar to John Earles solution but it means that you could style the last name separately to the first name

<h2>
    <!-- ko text: firstName --><!-- /ko --> 
    <span data-bind="text: lastName"></span>
</h2>
Sign up to request clarification or add additional context in comments.

Comments

3

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() });       
    }       
};

Sample: http://jsfiddle.net/rniemeyer/fLmXu/

Comments

3

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>​

1 Comment

Yes i understand this, but I am not able to change the html structure now. Is it possible to do this without html structure change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.