首页 > 解决方案 > 如何从只有孙子/孩子的 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);
    });

标签: javascripthtmljquery

解决方案


您正在将本机 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>


推荐阅读