在此示例中,有两个
div 元素,其ID为
div1 和
div2 ,每个元素均具有
style 属性。我们使用
getAttribute()来获取style属性的值。
我们必须单击给定按钮以获取给定div元素的
style 属性值。
<!DOCTYPE html> <html> <head> <title> The getAttribute Method </title> </head> <body> <p> Welcome to the lidihuo.com </p> <p> Example of the getAttribute() Method </p> <div id = "div1" style = "background-color: yellow; font-size: 25px; color: red; border: 2px solid red;"> This is first div element. </div> <br> <div id = "div2" style = "background-color: lightblue; font-size: 25px; color: blue; border: 2px solid blue;"> This is second div element. </div> <br> <button onclick = "fun()"> Click me! </button> <p id = "p"></p> <p id = "p1"></p> <script> function fun() { var val = document.getElementById("div1").getAttribute("style"); document.getElementById("p").innerHTML = val; var val1 = document.getElementById("div2").getAttribute("style"); document.getElementById("p1").innerHTML = val1; } </script> </body> </html>