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:
开发者_StackOverflow<span class="dot"></span>
<span class="dot active"></span>
<span class="dot"></span>
<span class="dot"></span>
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.
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
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"
- …
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.)
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/
精彩评论