Issue #1838💬 AnsweredOpened February 27, 2019by NicoEngler0 reactions

How to get the latest css property of a component?

快速解答by artf

I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes. First of all, be sure to store your templates correctly: Store and load templates in that case, when you set style via component.setStyle(...) on the next page reload you should be able to...

Read full answer below ↓

Question

Hi, awesome job with grapesjs!

I already read the docs (especially CssComposer) and also relevant issues but still, I am stuck.

A custom plugin allows me to add css to a component using component.setStyle(). On reload, I need my plugin to initialize with these values.

For example I want to read the margin property of a component. I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes.

Right now, I am parsing the property value manually with the assumption that the last entry represents the "active" entry. But that approach feels totally wrong! :)

function latestCSSPropertyValue(component, property) {
    let css = editor.CodeManager.getCode(component, 'css', {cssc: editor.CssComposer});
    let pos1 = css.lastIndexOf(property);
    let pos2 = css.indexOf(';', pos1);
    return (pos2 > pos1) ? css.substring(pos1, pos2).split(':')[1] : "";
}

I feel like I can achieve this differently with CssComposer but again, I am stuck.

Thanks, Nico

Answers (2)

artfMarch 3, 2019

I observed that css gets added inline when using setStyle() and once the data is stored and loaded, the css is defined in classes.

First of all, be sure to store your templates correctly: Store and load templates in that case, when you set style via component.setStyle(...) on the next page reload you should be able to get that style via component.getStyle(...) without the need to touch the CodeManager/CssComposer You might also want to take in account setRule/getRule if you need to manipulate CSS rules

lock[bot]March 10, 2020

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

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.