0

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>
5
  • 1
    It seems you've answered your own question. Just add a semi-colon after text-align: center, though I'm not even sure thats required. Commented Dec 5, 2012 at 18:32
  • Try to add a class instead. Commented Dec 5, 2012 at 18:32
  • 5
    h1Element.style.textAlign = "center"; Commented Dec 5, 2012 at 18:33
  • Yes, use a stylesheet and class names. Commented Dec 5, 2012 at 18:35
  • That would be referred to as a Cascading Style Sheet. It is an external document that defines styles for any number of elements on the page. Commented Dec 5, 2012 at 18:35

3 Answers 3

1

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:

<h1 id="headerExample1" style="color:blue;">This is a header</h1>

JavaScript:

var ex1 = document.getElementById('headerExample1');

if (someLogic) {
    ex1.style.textAlign = "center";
}

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 style property directly using JavaScript

HTML:

<h1 id="headerExample2" style="color:blue;">This is a header</h1>

JavaScript:

var ex2 = document.getElementById('headerExample2');

if (someLogic) {
    ex2.setAttribute('style', ex2.getAttribute('style') + ";text-align:center");
}

3 - CSS and classes - this is the cleanest way to style the header with regard to separation of concerns

HTML:

<h1 id="headerExample3">This is a header</h1>

CSS:

#headerExample3 {color:blue;}
.centered {text-align:center;}

​ JavaScript:

var ex3 = document.getElementById('headerExample3');

if (someLogic) {
    ex3.className = "centered";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Using inline styles is a bad idea because it is difficult to override them and maintaining separation of content and layout is important in web development.

Best to use a stylesheet:

h1 {
    color:blue;
    text-align:center
}

with JavaScript:

document.getElementsByTagName('h1').style.textAlign="center";

Comments

0

Use javascript: document.getElementById("h1id").style.textAlign = "center";

Replace the h1id above with the id you will provide in the html.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.