我正在尝试删除我孩子 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);
});
答案 0 :(得分:2)
您正在将原生 DOM 选择器与 jQuery 选择器混合使用 - 在 jQuery 领域中使用的方法是 .parent()
- 我还应该提到,无论如何删除所有内联样式并依赖正确构造的 CSS 会更好正确的样式和选择器的使用。
那么去除 attricture 的方法是 .removeAttr()
并列出实际的属性。
例如-此代码将起作用-因为它将从选择器的祖父元素中删除样式属性-但是将应用现有样式的闪光-在jquery函数工作之前-记住文档.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>