Sandrooco Sandrooco - 1 year ago 73
Javascript Question

Proper way to bind in tree structure with KnockoutJS

So I have the following "target/goal"-structure:

<p data-bind="text: Title" class="commentContent">
<a class="removeComment" data-bind="attr: {'data-commentId':Id}">x</a>

The anchor tag has to be in the paragraph. Now, as you can imaginge, the anchor tag is overwritten by the paragraph content.

What's the proper way to bind such stuff?

Answer Source

Here's how you could do that, using the containerless syntax to avoid extra DOM cluttering your page:

ko.applyBindings({ Title: "My fancy title", Id: 42 });
.commentContent { background: lime; padding: 10px; }
a { color: red; font-weight: bold; background: blue; }
<script src=""></script>

<p class="commentContent">
  <!-- ko text: Title --><!-- /ko -->
  <a class="removeComment" data-bind="attr: {'data-commentId':Id}">XanchorX</a>

You could also not use the containerless syntax, but use a span with a specific class instead, if you do need the extra markup to target it with certain CSS.

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