if I have an html element with predefined css style
<h1 style="color:blue;">This is a header</h1>
Now if I want to add a new style called text-align:center to h1 element.
How can I add a new style attribute to the end of the style attribute without overwrite the existing style?
So the result will look something like
<h1 style="color:blue;text-align:center">This is a header</h1>
Here’s three methods of doing this:
jsfiddle example
1 – set element style property – on the fly JavaScript styling, however arguably breaks separation of concerns
HTML:
JavaScript:
2 – set the style attribute – this is the dirtiest of the three but does give you an idea of how you can access/change the
styleproperty directly using JavaScriptHTML:
JavaScript:
3 – CSS and classes – this is the cleanest way to style the header with regard to separation of concerns
HTML:
CSS:
JavaScript: