Search code examples
jquerytextshow-hidetampermonkey

Hide a div based on a specific text contained within H4 tag


The html below is a condensed version of the Clicky.com home dashboard, I am looking to hide the forums div tag altogether that has an H4 tag containing the phrase "Clicky Forums".

<div class="fl small nounderline nowrap">
    <h4 class="inline">Clicky Forums</h4> &nbsp;
    <a class="no-ajax" href="/forums/">See more...</a>
    <br>&nbsp; &nbsp;
    <span class="">Sep 6</span>&nbsp;
    <a class="no-ajax" href="http://clicky.com/forums/?id=18929">Adding goal to form submission javascrip...</a>
    <br>&nbsp; &nbsp;
    <span class="">Sep 5</span>&nbsp;
    <a class="no-ajax" href="http://clicky.com/forums/?id=18928">no show visitor statistic</a>
    <br>&nbsp; &nbsp;
    <span class="">Sep 3</span>&nbsp;
    <a class="no-ajax" href="http://clicky.com/forums/?id=18924">Number of new visitors per url in a spec...</a>
    <br>
</div>

Solution

  • You can use JQuery to find all <h4> tags then check each one's .text() for a match. If found, .hide() the element's .parent() container.

    $('h4').each(function() {
      $el = $(this);
      
      if ($el.text() === 'Clicky Forums') {
        $el.parent().hide(); // or .remove()
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Stuff before</p>
    
    <div class="fl small nounderline nowrap">
        <h4 class="inline">Clicky Forums</h4> &nbsp;
        <a class="no-ajax" href="/forums/">See more...</a>
        <br>&nbsp; &nbsp;
        <span class="">Sep 6</span>&nbsp;
        <a class="no-ajax" href="http://clicky.com/forums/?id=18929">Adding goal to form submission javascrip...</a>
        <br>&nbsp; &nbsp;
        <span class="">Sep 5</span>&nbsp;
        <a class="no-ajax" href="http://clicky.com/forums/?id=18928">no show visitor statistic</a>
        <br>&nbsp; &nbsp;
        <span class="">Sep 3</span>&nbsp;
        <a class="no-ajax" href="http://clicky.com/forums/?id=18924">Number of new visitors per url in a spec...</a>
        <br>
    </div>
    
    <p>Stuff after</p>

    Note that this only hides the forum elements, you could also use .remove() to completely take them out of the DOM.

    Also note that this is a fairly fragile solution and can break if the title of the section changes at all (a single letter or capital difference will break the query). I'd recommend trying to find some more specific selector, like an ID, to identify the forum container.