jQuery:选择祖父母的h1标签

Sar*_*wic 0 html javascript css jquery

我在一个非常严格的框架(NetSuite)中工作,有一个小部分我可以直接控制下面的h3和p文本.结构类似于:

<div class="grandparent">
    <h1>Title Text</h1>
    <div class="otherstuff">Some text</div>
    <div class="parent">
        <h3>Text I have control over</h3>
        <p>More text I have control over</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我想为此页面隐藏标题文本和'.otherstuff'的内容.有多个页面与此类似,所以我正在寻找一种干净的方式来完成它.

我试过给h3标签一个类,然后是以下内容:

$('h3.myclass').parent().closest('h1').css('display','none);
Run Code Online (Sandbox Code Playgroud)

和变化但没有任何运气.我查看了.parentUntil()函数,但遇到了同样的问题.我抓住祖先元素没有问题,但在试图抓住那些祖先的元素时遇到了麻烦.

谁能帮我吗?

编辑:谢谢大家的时间和精力回答我的问题.对此,我真的非常感激!

Amm*_*CSE 9

  1. 使用closest()遍历到祖父母
  2. 使用find()选择所需的元素
  3. 您可以使用它们来hide()代替css('display', 'none')它们

var grandparent = $('.myclass').closest('.grandparent');
grandparent.find('h1, .otherstuff').hide();
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="grandparent">
  <h1>Title Text</h1>
  <div class="otherstuff">Some text</div>
  <div class="parent">
    <h3 class="myclass">Text I have control over</h3>
    <p>More text I have control over</p>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)