简体   繁体   中英

How do you change the background color of an <input> element with javascript

I have a <input> element that I want to change the background color on. The code I am currently using is this (but it is not working):

var allBlanksLoc = document.getElementById('text');
var allBlanks = allBlanksLoc.getElementsByTagName('input');

for(i=0; i<allBlanks.length; i++) {
var currentBlank = allBlanks[i];
var wordNum = blanks[i];
var blankWord = text[wordNum];
var usrAnswer = currentBlank.value;

if (usrAnswer != blankWord) {
currentBlank.style.backgroundColor = "red";
}
}

The third to last line being the most important

Update:

I fixed the camelCase on it but it still does not work. Any ideas of bugs there?

The full code is here: http://jsbin.com/imolo3/edit

Case is important. What you need is

document.getElementById('test').style.backgroundColor='red';

However

it would be better to use a css rule and use javascript only to add the class to the element.

CSS Rule

input.invalid {
    background-color: red;
}

Javascript

element.className = 'invalid';

它应该是backgroundColor - 注意大写C,JavaScript区分大小写。

Are you sure that this script is running at the right time? If it runs before the page is fully formed, the appropriate elements might not be present.

So not to repeat the solutions other users gave.

I personally use JQuery (and it's where any javascripter ends, overall for browser compatibility issues), and it would:

$(currentBlank).css("background-color","red");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM