源代码:
下载代码
AI 编程工具
点击运行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <style> div { border: 1px solid black; margin-bottom: 10px; } </style> </head> <body> <div> <h3>H3 元素</h3> <p>我是一个 p 元素,我的父元素是 div 元素。</p> </div> <div> <h3>H3 元素</h3> <p>我是一个 p 元素,我的父元素也是 div 元素。</p> </div> <p>点击按钮修改父元素为 div 的所有 p 元素的背景颜色。</p> <button onclick="myFunction()">点我</button> <p><strong>注意:</strong>Internet Explorer 8 及更早版本不支持 querySelectorAll() 方法。</p> <script> function myFunction() { var x = document.querySelectorAll("div > p"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; } } </script> </body> </html>
运行结果: