knocked loose
knocked loose

Reputation: 3304

Is it possible to hide elements that are above a matched html comment using jQuery?

I have a weird sort of use-case where our blogging tool appends a <!-- Read More --> into a post and anything above that gets pushed to our listing page.

What I want to do is find the matching comment, then tell any <p> tag above it (in the DOM) should be set to .hide() or .remove(). Here is what I have started, I'm not quite sure if I can select a .prevAll on an HTML comment.

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

You can see my fiddle here.

Is there anyway to go about accomplishing this task?

Upvotes: 0

Views: 36

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You could get any comments filtering nodeType and checking for specific value, e.g:

//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>

Upvotes: 5

Related Questions