How to append class to an element in prototype javascript framework?
I have this Prototype code at the top of my page
<script type="text/javascript">
if( window.location == 'http://example.com/about-us.html' ) {
$('about-us').addClassName('active');
}
</script>
and this html afer this javascript cod开发者_运维知识库e
<ul>
<li id="about-us">
<a href="#">
<span>About Us</span>
</a>
</li>
<li id="something-else">
<a href="#">
<span>Something Else</span>
</a>
</li>
</ul>
But even the address is correct http://example.com/about-us.html the class active is not append at all. I have tried alert and alert is working, so the condition is OK, however addclassname seems to not working.
What am I doing wrong? Thanks in advance.
That is how you do it. Be sure the code runs after the element is already on the page. In your case, that means the script
block you've quoted has to be after the list you've quoted, like this - live example, because you're not doing anything to delay the code. If you want the script
block to be above the list, you can do this:
document.observe("dom:loaded", function() {
// Your code here
});
Live example ...but you're usually better off just putting your scripts at the bottom of the body
element, just before the closing </body>
tag, as the YUI folks and others recommend.
If the element does exist at the time your code is running, my guess is that you're looking at the result HTML with "view source" or similar. Runtime changes to the DOM (including adding classes to elements) are not reflected in "view source", which is just a copy of the page as it was delivered from the server. You can use the "DOM" view in the developer tools built into most browsers (or Firebug for Firefox) to see the current state of the DOM tree.
精彩评论