是否可以使用jQuery隐藏匹配的html注释之上的元素?

时间:2017-11-22 16:19:08

标签: javascript jquery html

我有一种奇怪的用例,我们的博客工具会在帖子中添加<!-- Read More -->,而上面的任何内容都会被推送到我们的列表页面。

我想要做的是找到匹配的评论,然后告诉它上面的任何<p>标记(在DOM中)应该设置为.hide().remove()。以下是我的开始,我不太确定我是否可以在HTML评论中选择.prevAll

var content = $('.main').html();
//search for matching comment
var comment = content.match(/<!--.*?-->/);
alert(comment);
comment.prevAll('p').remove();

You can see my fiddle here.

无论如何都要完成这项任务?

1 个答案:

答案 0 :(得分:5)

您可以获取任何评论过滤nodeType并检查特定值,例如:

//find read more comment
$('*').contents().filter(function() {
  return this.nodeType === 8 && this.nodeValue.trim() === "Read More"; 
}).prevAll('p').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <p>
    jhkdsjhjlasfkdldfasdfd
  </p>
  <div>
    no-hide
  </div>
  <p>
    jhkdsjhjlasfkdldfasdfd
  </p>

  <!-- Read More -->

  <p>
    dfasfsfkljfaskf;sa
  </p>
  <!-- test -->
</div>