简体   繁体   中英

Javascript: how to change the style of all links in a page?

I'm trying to change the style of all links in a page via Javascript.

I tried both these but no success:

document.links.style.cursor = "wait";
document.getElementsByTagName(a).style.cursor = "wait";

What am I doing wrong?

var allLinks = document.links || document.getElementsByTagName('a');
for(var n=0;n<allLinks ;n++)
    document.allLinks [n].style.cursor = "wait";

The document.links is an array of elements, so document.links.style.cursor = "wait" equals to [link1,link2].links.style.cursor = "wait" .
And about document.getElementsByTagName(a) : the syntax is wrong, you forgot the quotes. The correct is document.getElementsByTagName("a")

var style = document.createElement("style");
document.head.appendChild(style);
try {
  style.innerHTML = "a { cursor: wait; }";
}
catch (_ie) {
  style.styleSheet.cssText = "a { cursor: wait; }";
}

Of course alternatively you could plan in advance for the eventuality of needing your links to change, and pre-load a static style sheet like this:

.wait-links a { cursor: wait; }

Then whenever you add the class "wait-links" to the <body> (or any container you like), the <a> tags will all be affected. That'd be much more efficient than iterating over the elements changing their individual styles (probably), though if there aren't many links it probably doesn't matter.

Using a style sheet for such things is, in my opinion, a much better practice. In this case, in fact, it'd be better not to call the class "wait-links", but rather use some word or words that describe what's actually happening. Then your JavaScript code just establishes the situation by adding (or removing) the class, and the style sheet controls the appearance changes. If you decide that in some cases the situation calls for the links to change color or become invisible, you can do that without having to root around in your scripts looking for style changes.

使用JQuery和“ .css”方法无需使用for循环,从而简化了代码。

$('a').css("cursor","wait");

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