1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>javascript Control class name in className attribute</title> 6 <style type="text/css"> 7 input{ 8 font-size: 12px; 9 } 10 .beijing{ 11 background-color: #4682B4; 12 color: #FFFFFF; 13 } 14 .guoqing{ 15 font-size: 20x; 16 font-weight: bold; 17 } 18 </style> 19 </head> 20 <body> 21 <div id="con" class="beijing">I want to visit Beijing this national day</div> 22 <form action="" method="post"> 23 <input type="button" name="" id="" value="Click Control" onclick="rec()"/> 24 </form> 25 <script type="text/javascript"> 26 var mychar=document.getElementById('con'); 27 document.write('here div Of clas Attribute value'+mychar.className)//output clas attribute 28 function rec(){ 29 mychar.className='guoqing';//change class Class name 30 // var myrec=confirm('How about Tiananmen Gate in Beijing'); 31 // if(myrec==true){ 32 // document.write('Yes, I want to'); 33 // }else{ 34 // document.write('What are you doing on National Day'); 35 // } 36 } 37 </script> 38 </body> 39 </html>
The className property sets or returns the class property of the element. The syntax is / / object.className = classname;
"Control class name attribute" function: 1. Get the class attribute of the element 2. Specify a css style for an element in the web page to change the appearance of the element
Test: set the style of the element through the className attribute:
1. Add "class name one" style to id="p1" element through className. When you click the "add style" button, the first paragraph of text adds a style.
2. Change the id="p2" element to the style of "class name two" through className. When you click the "change appearance" button, the second paragraph changes the style.
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 5 <title>className attribute</title> 6 <style> 7 body{ font-size:16px;} 8 .one{ 9 border:1px solid #eee; 10 width:230px; 11 height:50px; 12 background:#ccc; 13 color:red; 14 } 15 .two{ 16 border:1px solid #ccc; 17 width:230px; 18 height:50px; 19 background:#9CF; 20 color:blue; 21 } 22 </style> 23 </head> 24 <body> 25 <p id="p1" > JavaScript Make web page display dynamic effect and realize the function of interaction with users.</p> 26 <input type="button" value="Add styles" onclick="add()"/> 27 <p id="p2" class="one">JavaScript Make web page display dynamic effect and realize the function of interaction with users.</p> 28 <input type="button" value="Change appearance" onclick="modify()"/> 29 30 <script type="text/javascript"> 31 function add(){ 32 var p1 = document.getElementById("p1"); 33 p1.className="one"; 34 } 35 function modify(){ 36 var p2 = document.getElementById("p2"); 37 p2.className="two"; 38 } 39 </script> 40 </body> 41 </html>