我正在尝试删除祖父母的样式,然后删除我孩子的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);
});
发布于 2021-05-05 04:35:35
您正在将原生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>
https://stackoverflow.com/questions/67395193
复制相似问题