Issue #510✓ SolvedOpened November 12, 2017by asvine-p6 reactions

Add new class programatically

快速解答by artf4

@wemod123 editor.getWrapper().addClass('my-class')

Read full answer below ↓

Question

代码片段TEXT
Hello Artf,

I want to edit the styles of components (mostly imported html) without modifying all components with the  same class. I tried to add a random named class programmatically  like this:
`
      this.editor.on('component:selected', function(model) {
if (model && model.length > 2) {
                const uuid = this.s4(); // generate new random class name

                const selector =  {
                    name: uuid,
                    type: 'class',
                    label: uuid,
                };

                model[1].attributes.classes.push(selectorManager.get(uuid));
     let mClasees = model[1].attributes.classes;
             const uuid = this.s4();
             const selector =  {
                 name: uuid,
                 type: 'class',
                 label: uuid,
             };
          mClasees.push(selector);

      
}.bind(this));
`

This add a class programmatically to the component but it seem to no let me edit it's style. 

I just want be able to change the style of a single component without having to care which class it belongs to. Event if I copy past a component, I want be able to edit each components individually.
I hope that clear. If you need any further information, don't hesitate to ask me :) 
Thanks your help!

Answers (3)

👍 Most helpfulartfJanuary 2, 2020

@wemod123 editor.getWrapper().addClass('my-class')

artfFebruary 13, 2019

@IrinaCodixis from the https://github.com/artf/grapesjs/releases/tag/v0.14.52 we've added setRule/getRule methods, so to add some CSS rule programatically you should do this:

editor.CssComposer.setRule('.some-class', { color: 'red' })

// Remove
const rule = editor.CssComposer.getRule('.some-class');
editor.CssComposer.getAll().remove(rule);
artfNovember 14, 2017

You mean something like model.set('style', {...})? This adds an inline style on the component

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.