简体   繁体   中英

Change Class of element using getElementById

I have a menu structure like this:

 <ul> <li> <h3>pageA</h3> <ul> <li id="a1"><a href="index.php?pageA&id=1">1</a> </li> <li id="a2"><a href="index.php?pageA&id=2">2</a> </li> <li id="a3"><a href="index.php?pageA&id=3">3</a> </li> <li id="a4"><a href="index.php?pageA&id=4">4</a> </li> <li id="a5"><a href="index.php?pageA&id=5">5</a> </li> </ul> </li> <li> <h3>pageB</h3> <ul> <li id="b1"><a href="index.php?pageB&id=1">1</a> </li> <li id="b2"><a href="index.php?pageB&id=2">2</a> </li> <li id="b3"><a href="index.php?pageB&id=3">3</a> </li> <li id="b4"><a href="index.php?pageB&id=4">4</a> </li> <li id="b5"><a href="index.php?pageB&id=5">5</a> </li> </ul> </li> </ul>

And I want to change <li> classes with javascript. I can change child <li> with following code. But i can't change class of parent <li> .

 document.getElementById("a1").className = 'active';

Your solution should work to replace the class of an element with that ID.

Check out this page: http://www.w3schools.com/jsref/prop_html_classname.asp

Example Overwriting an existing class name with a new one:

<div id="myDIV" class="mystyle">I am a DIV element</div>

document.getElementById("myDIV").className = "newClassName";

Example To add a class to an element, without overwriting existing values, insert a space and the new class name:

document.getElementById("myDIV").className += " anotherClass";

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