Search code examples
javascriptcssattributesgetcomputedstyle

Removing inline CSS affects styles defined in stylesheet


I'm facing a strange behavior.

I have a script that applies inline CSS to elements from its stylesheet with computedStyle method.

This is a way to copy rich text instead of plain text.

But after the copy, I need to delete the style="" attribute.

When this happens, some style attributes (like color, disappears) while I can see in the inspector that this attribute is still linked to my element by its class.

See there : https://jsfiddle.net/sxybrcug/ (color disappears but border-color is okay)

Do you know what's happening ?

Thanks


Solution

  • It looks like inline styles are being added to your container div as well, but on the button click, only the inline styles on the <p> elements are removed. So p continues to inherit the inline styles of container, specifically, -webkit-text-fill-color, which is set to black, overriding the color property.

    If you add

    container.setAttribute("style", "");
    

    to your click listener, it removes all the inline styles and the color of the p elements shows as red.