3

I got a simple JavaScript that changes the inner HTML of an element when links are clicked, it looks like this:

function changeHeader(Index)
{
    var headers = new Array("Coffee tables","Side tables","Stand tables","Dinner tables","Stools","Pedestals");
    document.getElementById("header").innerHTML = headers[Index];

}

The CSS for header is below:

#header
{
    cursor: hand; 
    cursor: pointer;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

And the HTML is basically this:

<p id="header">Press a link</p>
<a href=# onclick="changeHeader(1)">Coffee tables</a>
<a href=# onclick="changeHeader(2)">Side tables</a>
<a href=# onclick="changeHeader(3)">Stand tables</a>

And so on. My problem is that I'd like to have different background colors on the header element depending on what link is pressed. The first link might get a red background, the second a blue, the third a green and so on..

How can I use JavaScript to add a property to an already existing CSS id? I don't use jQuery, so only pure JavaScript please :)

4 Answers 4

18

You could use style property

document.getElementById("header").style.backgroundColor = 'red';
Sign up to request clarification or add additional context in comments.

1 Comment

background-color should be: backgroundColor
1

You can change your approach a little:

function changeHeader(Index) {
    var headers = [
        {color: 'red', text: "Coffee tables"},
        {color: 'blue', text: "Side tables",
        {color: '#DDD', text: "Stand tables"},
        {color: "#ACD12A", text: "Dinner tables"},
        {color: "Chuck Norris", text: "Stools"}
    ];
    var header = document.getElementById("header"),
    header.innerHTML = headers[Index].text;
    header.style.backgroundColor = headers[Index].color;
}​

Comments

0

You don't need to add an additional property to the ID, either you add inline-styling to the element, or if you don't want to use inline-styling you add an additional class to the element instead, that sets the proper background color.

Here is an example of how you can add/remove classes from an element, without using jQuery: http://snipplr.com/view/3561/addclass-removeclass-hasclass/

Comments

0

See sample code in this page : http://jsfiddle.net/Rd4y5/

js :

d = document.getElementById("d1");
console.log(d.style);
d.style.backgroundColor="red";
d.style.width = "300px";
d.style.height="300px";
    console.log(d.style);

html :

<div id='d1'>a<div>​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.