如何通过浏览器控制台将页面所有p标签文字颜色设置为白色
失效原因
document.p不是合法的DOM访问接口,执行时会返回undefined,自然无法设置样式。document.body可以直接调用是因为每个HTML页面有且仅有一个<body>标签,它是document对象的内置属性;但页面中<p>标签数量不固定,不存在对应的document.p内置属性,你的写法从根上就不成立。
可行方案
根据需求选下面任意一种写法即可:
- 遍历现有p标签设置行内样式
只会修改当前页面已经存在的p标签,后续动态加载的新p标签不会被影响:document.querySelectorAll('p').forEach(pEl => { pEl.style.color = '#fff' }) - 注入全局CSS规则
所有p标签(包括后续动态新增的)都会自动应用白色文字样式,不需要反复执行:const globalStyle = document.createElement('style') globalStyle.textContent = 'p { color: #fff !important; }' document.head.append(globalStyle)
内容的提问来源于stack exchange,提问作者Luminesence
相关产品推荐
相关产品推荐

