0

Is it possible to set the html element in knockout.js programmatically? For example, the user can choose the heading level (from h1 - h6 and p if it's no heading). And in frontend I then have a variable data.headingLevel which contains the html tag.

Currently I'm doing it like this, which is working. But I absolutely hate it to do it like that.

<h1 if="data.headingLevel == 'h1'" html="data.text"></h1>
<h2 if="data.headingLevel == 'h2'" html="data.text"></h2>
<h3 if="data.headingLevel == 'h3'" html="data.text"></h3>
<h4 if="data.headingLevel == 'h4'" html="data.text"></h4>
<h5 if="data.headingLevel == 'h5'" html="data.text"></h5>
<h6 if="data.headingLevel == 'h6'" html="data.text"></h6>
<p if="data.headingLevel == 'p'" html="data.text"></p>

Can we do this in one line by binding the element tag?
Something like this:

<p data-bind="element: data.headingLevel" html="data.text"></p>

In the line above I'd love for the <p> to simply switch to the variables element.
I don't want to insert a new child element. (Like the component binding does)

1 Answer 1

0

If you are going to use dynamic html content like your example you could do

var element = "h1";
var data = "My h1 content"

ko.applyBindings({ bar: `<${element}>${data}</${element}>`})

https://jsfiddle.net/tLwq1rab/

If you you want your content to be databound knockout I would use tample binding. Were the template dictates what element is rendered

Not the answer you're looking for? Browse other questions tagged or ask your own question.