- Objective: - Breadcrumb: DOM - Document - 实例方法 # 概念阐释 ## 语义 `getElementById`是一种 JavaScript 方法,可以在HTML文档中获取到指定的id(`#myId`)元素。然后赋这个元素一些js代码,获得前端样式修改的效果。 ## 语法 ```js const myId = document.getElementById('id'); ``` # 实例 ```html <div id="myDiv">Hello World!</div> <script> var myElement = document.getElementById("myDiv"); console.log(myElement.innerHTML); </script> ``` 通过[[js DOM 修改内容 innerHTML属性]]得到控制台中打印出"Hello World!" ```html <img id="myImage" src="example.jpg"/> <script> var myImage = document.getElementById("myImage"); myImage.style.width = "50%"; </script> ``` 通过[[js DOM 修改样式 style属性]]方法修改图1片的宽度。 # 相关内容 # 问题 费曼这段代码:为什么不是访问button? ```html <!DOCTYPE html> <html> <head> <title>getElementById example</title> </head> <body> <p id="para">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button> </body> </html> ``` ```js function changeColor(newColor) { var elem = document.getElementById('para'); elem.style.color = newColor; } ``` # 问题答案 [答案](https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementById) js文件: 创建一个改变颜色的函数: 1. 获取要改变颜色的html内容`var elem = document.getElementById('para');` 2. 用`.style`属性修改CSS字体颜色属性`color`,等于新的参数 HTML文件: 1. 在button中加入[Notification接口](https://developer.mozilla.org/zh-CN/docs/Web/API/Notification/click_event)`onclick` ,调用改变颜色函数,第一个button的参数为blue,第二个button的参数为red # 参考资料 [onclick - MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/Notification/click_event)