From Trix's documentation of insertHTML
:
Trix will first convert the HTML into its internal document model.
During this conversion, any formatting that cannot be represented
in a Trix document will be lost.
...Which means if Trix cannot understand an attribute, it won't put
that attribute into the resulting HTML, so you have to find another
way out.
There is a hack to force Trix preserve the attributes of an element,
involving Trix attachments. Its main downside is that you can no
longer edit it in Trix. Additionally, you element will be wrapped in
a <figure>
, and while formatting can always be worked around by
appending an override stylesheet after Trix's, there isn't a silver
bullet for the semantic problems.
The JavaScript for this is:
/* programmatically construct DOM to prevent XSS */
const span = document.createElement('span');
span.id = userId;
span.className = 'mention-user';
span.append(userName);
element.editor.insertAttachment(
new Trix.Attachment({
content: span.innerHTML,
})
);
Or, in jQuery:
const span = $('<span>')
.attr('id', userId)
.addClass('mention-user')
.append(new Text(userName));
element.editor.insertAttachment(
new Trix.Attachment({
content: span[0].innerHTML,
})
);
For the daring, you can also hack Trix to add support for id
, class
,
and other attributes. How this should be accomplished is left as an
exercise for the reader.