<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> div { width: 300px; height: 400px; border: 1px solid red; } </style> </head> <body> <input type="button" value="显示效果" id="bt"/> <div id="dv"> <span>我是span</span> <p>我是p</p> <span>我是span</span> <p>我是p</p> <span>我是span</span> <p>我是p</p> <span>我是span</span> <p>我是p</p> <span>我是span</span> <a href="http://www.baidu.com">百度</a> </div> <script src="common.js"></script> <script> my$("bt").onclick = function () { //先获取div var dvObj = document.getElementById("dv"); //获取里面的所有子节点 var nodes = dvObj.childNodes; //循环遍历所有的子节点 for(var i = 0; i < nodes.length; i++) { //判断这个子节点是不是p标签 if(nodes[i].nodeType == 1 && nodes[i].nodeName == "P") { nodes[i].style.backgroundColor = "red"; } } }; </script> </body> </html>
原文地址:https://www.cnblogs.com/cuilichao/p/9374856.html
时间: 2024-10-13 10:23:03