隐藏所选<span>

时间:2018-06-18 11:47:46

标签: javascript jquery html css

道歉,标题可能有点令人困惑。

我有多个<div>'会自动生成。

<div class="item">
  <div class="item-inner  selected">
    <div class="checkbox-row">
      <span class="fakelabel">
        <input id="id_300622" type="checkbox" name="id_300622" checked="checked">
        <span>Marketing</span>
        <span>Email</span> <span> | </span>
        <span>Blog | Subscription</span>
      </span>
    </div>
    <p>Receive timely updates with the latest blog posts.</p>
  </div>
</div>

<div class="item">
  <div class="item-inner  selected">
    <div class="checkbox-row">
      <span class="fakelabel">
        <input id="id_4849126" type="checkbox" name="id_4849126" checked="checked">
        <span>Careers Subscription</span>
      </span>
    </div>
    <p>Receive timely updates with the latest blog posts.</p>
  </div>
</div>

我上面的代码段,我希望前三个spandisplay:none;,因此它只显示<span>Blog | Subscription</span>代码。

我可以实现以下内容来隐藏标记:

.fakelabel span:nth-child(2) {
    display: none;
}

但是,执行上述操作还会隐藏第二个div中的“职业订阅”文本。

理想情况下,我希望最后<span>始终在每个div中可见,并隐藏任何其他div。但我不确定如何处理这个问题?

注意:我无法改变HTML,因为HTML代码是通过HubSpot自动生成的(痛苦!)。这可以通过JavaScript / CSS吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用not()选择器:

.fakelabel span:not(:last-child) {
  display:none;
}
<div class="item">
  <div class="item-inner  selected">
    <div class="checkbox-row">
      <span class="fakelabel">
        <input id="id_300622" type="checkbox" name="id_300622" checked="checked">
        <span>Marketing</span>
        <span>Email</span> <span> | </span>
        <span>Blog | Subscription</span>
      </span>
    </div>
    <p>Receive timely updates with the latest blog posts.</p>
  </div>
</div>

<div class="item">
  <div class="item-inner  selected">
    <div class="checkbox-row">
      <span class="fakelabel">
        <input id="id_4849126" type="checkbox" name="id_4849126" checked="checked">
        <span>Careers Subscription</span>
      </span>
    </div>
    <p>Receive timely updates with the latest blog posts.</p>
  </div>
</div>

答案 1 :(得分:0)

  

理想情况下,我希望最后<span>始终在每个div中可见,并隐藏任何其他div。但我不确定如何处理这个问题?

使用:not语法和last-of-type选择器。

.fakelabel span:not(:last-of-type) {
  display: none;
}
<div class="item">
  <div class="item-inner  selected">
    <div class="checkbox-row">
      <span class="fakelabel">
        <input id="id_300622" type="checkbox" name="id_300622" checked="checked">
        <span>Marketing</span>
      <span>Email</span> <span> | </span>
      <span>Blog | Subscription</span>
      </span>
    </div>
    <p>Receive timely updates with the latest blog posts.</p>
  </div>
</div>

<div class="item">
  <div class="item-inner  selected">
    <div class="checkbox-row">
      <span class="fakelabel">
        <input id="id_4849126" type="checkbox" name="id_4849126" checked="checked">
        <span>Careers Subscription</span>
      </span>
    </div>
    <p>Receive timely updates with the latest blog posts.</p>
  </div>
</div>