简体   繁体   中英

Changing html element property via javascript does not change appearance

I have got a html page, with a navigation bar. Ideally, once user select one option, that option background image would change. However, I was not able to achieve that, by using javascript to dynamically change the list property.

The html:

<html>
<head>
<link href="includes/css/content.css" rel="stylesheet" type="text/css">
<script>
function select(id)
{
    alert(id);
    var list = document.getElementsByTagName('li');
    for(var i=0;i<list.length;i++)
    {
        list[i].class='random';
    }
    document.getElementById(id).class='selected';
}
</script>
</head>
<body>
<div id="mainContent">
            <div class = 'nav'>
                <ul>
                    <li class='selected' id='home' onClick="select(this.id)"><a href="#" ><span  style='color:gray'>Home</span></a></li>
                    <li id='system' onClick="select(this.id)"><a href="#" ><span  style='color:gray'>Systems</span></a></li>
                    <li id='temp' onClick="select(this.id)" ><a href="#"><span  style='color:gray'>Notification Template</span></a></li>

                </ul>
        </div>
</body>
</html>

And the css file looks like this:

.nav .selected a{
background-size:cover;
background: url(../images/nav.gif) no-repeat top;
color:white;
}

Is there something I am doing wrong here?

The property class does not exist for HTMLElement. Use className to set the css class.

For a full list of properties - see http://www.w3schools.com/jsref/dom_obj_all.asp

如果您以这种方式设置类,则需要使用.className [ https://developer.mozilla.org/en-US/docs/DOM/element.className ]

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