简体   繁体   中英

Why doesn't this simple, one line javascript code work?

using google chrome, i don't know why this doesn't work :(

// ==UserScript==
// @name       My Fancy New Userscript
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match      http://*/*
// @copyright  2012+, You
// ==/UserScript==

document.getElementsByTagName('a').style.color='Red';

Because it returns an "array-like" collection of elements that you need to operate on individually.

document.getElementsByTagName('a')[0].style.color='red';

If you anticipate multiple matches, you'd operate in a loop.

var aList = document.getElementsByTagName('a');

for (var i = 0, len = aList.length; i < len; i++) {
    aList[i].style.color='red';
}

Of course for this simple operation, you'd probably use CSS instead of JS.

If you only want links, you can use document.links instead of getElementsByTagName .

document.getElementsByTagName returns a NodeList . You'd have to do something like the following:

var anchors = document.getElementsByTagName('a'), i, j;
for (i=0, j=anchors.length; i<j; i++) {
    anchors[i].style.color = 'red';
}

getElementsByTagName returns a NodeList , not just one element. You need to loop through and edit each one's style.color .

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