jquery删除元素,如果没有文本在它之后

时间:2017-07-26 03:08:31

标签: jquery html

我在尝试理解如何在找不到文本后删除此元素时真的很难

示例HTML

<ul>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <b class="warning">Comments:</b>
</ul>

<ul>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <b class="warning">Comments:</b>Keep b.warning element if text appears after it
</ul>

我希望它看起来像这样,在b.warning之后找不到文字

<ul>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
</ul>

<ul>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <li>Keep This Text
      <a>Keep This Text</a>
   </li>
   <b class="warning">Comments:</b>Keep b.warning element if text appears after it
</ul>

1 个答案:

答案 0 :(得分:2)

只需使用此行:

if($('b')[0].nextSibling) {
  $('b')[0].nextSibling.nodeValue = '';
  $('b.warning').hide();
}

这是工作小提琴:

http://jsfiddle.net/cfgr9/532/

感谢@nnnnnn和@samuel对评论的帮助。