slwr
slwr

Reputation: 1175

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?

Upvotes: 1

Views: 963

Answers (3)

Obada_alhumsi
Obada_alhumsi

Reputation: 95

Using the JQuery and the ".css" method removes the need to have a for loop and simplifies the code.

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

Upvotes: 0

Pointy
Pointy

Reputation: 413966

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.

Upvotes: 3

Danilo Valente
Danilo Valente

Reputation: 11352

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")

Upvotes: 6

Related Questions