Issue #893✓ SolvedOpened February 23, 2018by alimajed933 reactions

Add attribute to HTML

快速解答by nojacko2

I think you need to add the attribute to the model, rather than the view. https://github.com/artf/grapesjs/blob/50cc585f23f2560077fd0e9a42ced22e67e69723/src/dom_components/model/Component.js#L298 Then, you'll need to render the view. I think it's like this, but no guarantees 😄

Read full answer below ↓

Question

Hello everyone,

I want to add an id for each block I drag and drop in the canvas; To be more clear, I do not want to add an Id for each type, per example: Image, Table, Box, ... I want to add ad Id for each block, which means per example, the block "1 section" becomes <table ... blockId = 1>.

I am trying to use those 2 commands:

  • editor.getSelected().view.$el[0].setAttribute("blockId","1")

  • editor.getSelected().get('components').trigger('resetNavigator')

Yes the changes do appear on the canvas if I do "Inspect Element", but If I try to export the HTML code of the template, the attribute is not added.

Any idea how to achieve that and make the changes appear in the exported code too?

Thank you in advance.

Answers (3)

ezp127July 4, 2019

Hello, Just leaving an example in case someone else needs.

editor.on('block:drag:stop', function(model) {
	model.addAttributes({ 'data-block_id': '123xyz' });
});
artfMarch 2, 2018

Just like James suggested but without selected.view.render() as the view will receive changes simultaneously

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Free option

Check the open-source GrapesJS plugins on GitHub or run a quick search in our free catalog.

Browse free plugins →
Premium option

Premium plugins ship with support, regular updates, and production-ready features — save days of integration work.

Browse premium plugins →

Related tutorials

In-depth guides on the same topic.

All tutorials →

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.