0
<style type="text/css">
    td.a{
        background: yellow
    }
</style>

<table><td class="a"></td></table>

Above is a html/css code snippet. From it, you can know that the background colour of td portion is in yellow.

Later, I have added a html select drop down component. I hope to change the background colour from yellow to blue when I select another select drop down value. but I do not know how to do.

This should be a question related to changing css through Javacript. It is quite similar with this How to change HTML background with JavaScript Function? but u can see that my td component does not have id, it just has class.

Hope someone can help me, thank you.

1
  • Well, the obvious solution is to either give your td an id, or use document.getElementByClassName. Edit: for your reference Commented May 24, 2015 at 9:05

2 Answers 2

2

Assuming the colour you want to change the background of the cells (I'm assuming you'll have more than just the one) to is newColor then;

var tds = document.getElementsByClassName('a');
for (var x = 0; x < tds.length; x++) {
  tds[x].style.background = newColor;
}
Sign up to request clarification or add additional context in comments.

Comments

1

For changing all elements with the class name

var elements = document.getElementsByClassName("a");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor="blue";
}

Or to change a single element, as long as you know it's position.

var elements = document.getElementsByClassName("a");
elements[positon].style.backgroundColor="blue";//in your example position would be 0

If you give your element an id you can use the following

document.getElementById("idforelement").style.backgroundColor = "blue";

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.