javascript - 如何从只有孙子/孩子的 id 的祖父母和父母中删除样式。(jQuery)
问题描述
我正在尝试删除祖父母的样式,然后是我孩子 id 的父元素。比如~>
<div>
<div>
<div id='screenSelector'>
</div>
</div>
</div>
但是它在控制台中返回一个错误,指出Cannot read property 'parentElement' of null
我将如何解决这个问题?
这是我当前的代码〜> 提前感谢您的所有帮助和时间。
$(document).ready(function() {
document.getElementById("screenSelector").parentElement.parentElement.removeAttribute("style");
document.getElementById("screenSelector").parentElement.removeAttribute("style");
document.getElementById("runButtonWrapper").parentElement.parentElement.removeAttribute("style");
document.getElementById("runButtonWrapper").parentElement.removeAttribute("style");
$("body").append(themeChangesCss);
});
解决方案
您正在将本机 DOM 选择器与 jQuery 选择器混合使用——在 jQuery 领域中使用的方法是.parent()
——我还应该提到,无论如何删除所有内联样式并依赖于正确构造的 CSS 以及正确的样式和使用选择器会更好。
然后删除属性的方法是.removeAttr()
列出的实际属性。
例如-此代码将起作用-因为它将从选择器的祖父元素中删除样式属性-但是将应用现有样式的闪光-在jquery函数起作用之前-记住document.ready意味着这将仅在加载 DOM 内容后激活 - 在此示例中,在删除样式属性之前会出现红色文本。
$(document).ready(function() {
// the following removes the color: red style attribute from the granparent element
$("#screenSelector").parent().parent().removeAttr('style')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="color: red;">
GrandParent
<div style="color: blue">
Parent
<div id='screenSelector' style="color: green">Child</div>
</div>
</div>
推荐阅读
- java - 无法使用 Zulu JRE (8.271) 在 macOS 上运行 Jar 文件
- javascript - LogBox 忽略在本机反应中不起作用的警告?
- git - git不允许我创建空目录
- vim - 我的 VIM 配置不适用于 autocmd 插件
- javascript - 在不同的功能中多次获取 DOM 元素是不好的做法吗?
- android - 我正在测试我的 Flutter App 上的评论。注释过多时,应用程序显示黄色条 右侧 175 像素
- sql - 我怎样才能最好地旋转我的红移表?
- javascript - 如何检查 Javascript 数组是否包含另一个数组的所有其他元素
- javascript - 即使有依赖关系,useEffect 也会无限地调度一个动作
- javascript - import mobx-state-tree throws Uncaught TypeError: Object(...) is not a function