LA_
LA_

Reputation: 20409

How to change class of element based on javascript variable value?

I have the following script:

<script>
  window.now = some_int_value;
</script>

and the following html:

<span class="dot"></span>&nbsp;
<span class="dot active"></span>&nbsp;
<span class="dot"></span>&nbsp;
<span class="dot"></span>&nbsp;

How should I change the style of the dot in accordance with window.now value? So, if it is equal to 1, then first dot should be 'dot active', if equal to 2, then second and so on.

Upvotes: 0

Views: 580

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 185893

This should do it:

var dots = document.querySelectorAll( '.dot' );

[].slice.call( dots ).forEach( function ( dot, i ) {
    dot.className = 'dot' + ( window.now === i + 1 ? ' active' : '' );
});

(This doesn't work in IE8.)

Live demo: http://jsfiddle.net/dKDLx/

(The demo shows that even though the 2. dot had the class "active" set, window.now = 3; will cause that class to be "moved" to the 3. dot.)

Upvotes: 1

vzwick
vzwick

Reputation: 11044

You should consider looking into jQuery, which simplifies working with the DOM a lot.

This is all you'd need for your indicator in jQuery:

$('span.dot').eq(window.now - 1).addClass('active');

No more

  • "Maybe I should assign an ID to each dot"
  • "getElementByTagName() is not implemented in some more or less obscure browser".
  • "This won't work in IE8"

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78520

document.getElementsByClassName("dot")[window.now-1].className += " active";

You can do that (for IE9+ and all other major browsers).

Or you can use

document.querySelectorAll(".dot")[window.now-1].className += " active";

for IE8+, FF3+, and all other major browsers.

or you can combine them

if(document.getElementsByClassName);
    document.getElementsByClassName("dot")[window.now-1].className += " active";
else if(document.querySelectorAll)
    document.querySelectorAll(".dot")[window.now-1].className += " active";

Compatibility Documentation

Upvotes: 1

Niall Cairns
Niall Cairns

Reputation: 88

This isn't, by any chance, supposed to be a 4-dot progress bar/throbber? If so, I'd say just use a gif - there's a site that can generate them for you: http://preloaders.net/

Upvotes: 0

Related Questions