如何使用javascript更改元素的颜色

如何使用javascript更改元素的颜色,javascript,colors,Javascript,Colors,我正在上javascript初学者课程。我的老师想让我改变页面中某个元素的颜色,但我不知道怎么做。以下是网页: // JavaScript Document function myPar() { pge = new Array () //I would need to change the color of JUST pge[4] pge[4] = "So have you reverse engineered this document?" pge[3

我正在上javascript初学者课程。我的老师想让我改变页面中某个元素的颜色,但我不知道怎么做。以下是网页:

// JavaScript Document

function myPar() {

    pge = new Array ()

    //I would need to change the color of JUST pge[4]

    pge[4] = "So have you reverse engineered this document?"

    pge[3] = "This first instance a button creation will create multiple buttons with no purpose. They will not be linked to any site in this lecture video. The first need to become familiar with the process and with the required syntax for setting a series of attributes. When the button construction sequence is completed the process will then append the button to the body tag as it did for the paragraph tag."

    pge[2] = "The same process that was used to create paragraphs dynamically will be used to create buttons dynamically. This first instance of button creation will be design to create a button each time the function trigger is pressed."

    pge[5] = "So this build of page content can happen in any sequence that is seen fit and then modified by changing index vaues."

    pge[0] = "It was the best of times, it was the worst of times"

    pge[1]= "There's no way that we can work out a way to colonize Mars in the next 50 years.  Think of the logistical obstacles to such a plan.  You'd need food, water, medicine.  You'd need engineers, doctors, nurses, endless oxygen, of which mars has none."  

    pge[6] = "So what is such a big deal here?" 


    for (i=0;i<=pge.length-1;i++) {
        var pgp = document.createElement("p");
        var txt = document.createTextNode(pge[i]);

        pgp.appendChild(txt);
        pgp.setAttribute("class","mine");

        pgp.appendChild(document.createElement("br"));

        pgp.setAttribute("style","color:#605;font-size:1.5em;");

        document.body.appendChild(pgp);
        txt = "";
    }

}
//JavaScript文档
函数myPar(){
pge=新阵列()
//我只需要更改pge的颜色[4]
pge[4]=“那么您是否对该文档进行了反向工程?”
pge[3]="第一个按钮创建实例将创建多个无目的的按钮。它们不会链接到本课程视频中的任何站点。第一个实例需要熟悉该过程以及设置一系列属性所需的语法。当按钮构建序列完成时,该过程将追加按钮与段落标记一样,添加到正文标记。”
pge[2]=“动态创建段落的过程将用于动态创建按钮。此按钮创建的第一个实例将设计为在每次按下功能触发器时创建按钮。”
pge[5]=“因此,页面内容的构建可以按任何顺序进行,只要认为合适,然后通过更改索引值进行修改。”
pge[0]=“这是最好的时代,也是最糟糕的时代”
pge[1]=“我们不可能在未来50年内找到殖民火星的方法。想想这样一个计划的后勤障碍。你需要食物、水、药品。你需要工程师、医生、护士和无穷无尽的氧气,而火星没有这些。”
pge[6]=“那么这里有什么大不了的?”

对于循环中的(i=0;i,请检查
i
的值。如果值为4,则是您要更改的值。因此,您可以执行以下操作:

var len = pge.length;
for (var i=0; i< len;i++) { 
 if (i==4) { pgp.classList.add('redBG'); }
}
更新
的最佳方法不是使用
setAttribute
。它是通过修改
类列表
(对于现代浏览器)。在较旧的浏览器中,您必须手动将
类名
作为字符串进行操作

此外,您应该始终
var
变量

.redBG {background-color:red; }