getElementsByTagName不更改颜色

时间:2015-08-08 20:17:34

标签: javascript html

有没有像css这样的方法,我们可以用javascript改变颜色到标签,我尝试了getElementsByTagName但没有任何反应。

我尝试搜索谷歌,但遗憾的是没有找到,这就是为什么我在这里问这个基本的javascript问题,感谢你的答案提前...

此代码无效...

HTML:

<p id="demo"> test test test test test</p>

<span id="demoz"> test2 test2 test2 test2 test2</span>

使用Javascript:

document.getElementById('demo').style.background = "green";

document.getElementsByTagName('span').style.background = "green";

的jsfiddle:

http://gadgets.ndtv.com/mobiles/news/paid-membership-no-longer-required-to-develop-and-test-ios-apps-swift-2-will-be-open-source-701507

4 个答案:

答案 0 :(得分:5)

这是因为document.getElementsByTagName('span')会产生一个类似数组的对象(好吧,你可以在一个页面上有多个span标签,对吗?)。

要更改此函数返回的每个(span)元素的背景颜色,您将迭代返回的数组(类似对象):

var spanElements = document.getElementsByTagName('span');

for (var i = 0; i < spanElements.length; i++) {
    spanElements[i].style.background = 'green';
}

See the updated JSFiddle

或者,如果你只是针对单个span元素,返回数组中的第一个元素,你可以这样做:

document.getElementsByTagName('span')[0].style.background = 'green';

答案 1 :(得分:2)

返回NodeList

document.getElementsByTagName('span')[0].style.background = "green";

答案 2 :(得分:1)

是 - 检查出来:

http://jsfiddle.net/gratiafide/gj0g5ysr/

using (SqlCommand cmd = new SqlCommand("SELECT * FROM motorista where id = " + driverId +" order_by data_atualizacao", connection))
{
    connection.Open();

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        // Check is the reader has any rows at all before starting to read.
        if (reader.HasRows)
        {
            // Read advances to the next row.
            while (reader.Read())
            {
                motorista motorist = new motorista();
                // To avoid unexpected bugs access columns by name.
                motorist.id = reader.GetInt32(reader.GetOrdinal("id"));
                motorist.nome = reader.GetString(reader.GetOrdinal("nome"));
                motorist.numero_registro = reader.GetString(reader.GetOrdinal("numero_registro"));
                morotistList.Add(motorist);
            }

            return morotistList.ToList();
        }
    }
}

GetElementsByTagName返回一个集合,类似于数组

答案 3 :(得分:1)

尝试将document.querySelector()与选择器"span[id=demoz"])一起使用,以指定span个元素id="demoz"来设置background

document.getElementById("demo").style.background = "green";

document.querySelector("span[id=demoz]").style.background = "green";
<p id="demo"> test test test test test</p>

<span id="demoz"> test2 test2 test2 test2 test2</span>

jsfiddle http://jsfiddle.net/3j0vokLd/3/