Not able to add attribute like Id or class for any tag in trix-editor while inserting HTML programmatically
Asked Answered
D

2

12

I am trying to add attribute like id, class for span tag in trix-editor while inserting the html through java-script but when I checked the DOM for that tag, editor removing the added attributes from tag.

My Java-script code to insert html with attribute:

element.editor.insertHTML("<span id='" + userId + "' class='mention-user'>" + userName + "</span >"); 

DOM:

 <div><!--block-->@<span style="font-size: 12px;">abc/span></div></trix-editor>

Even I have tried:

element.editor.activateAttribute("href", "https://trix-editor.org/");

this is working fine but not able to add id or class. can anybody have an idea to add id or class in tag?

Denunciate answered 4/7, 2018 at 7:45 Comment(0)
I
0

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.

Izzard answered 18/2 at 2:33 Comment(0)
F
-3

You can use it with more than 1 way

plain js :

document.getElementsByTagName("span")[0].setAttribute("class", "mention-user");

document.getElementsByTagName("span")[0].setAttribute("id", userId);

or jquery:

$("span").attr("id",userId);
$("span").attr("class","mention-user");

Not sure why but you use insertHtml dont know if you can add id or class with it hope that answer your question

Felspar answered 21/6, 2019 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.