Home > Blockchain >  Hide specific text on load but use same text to identify element for click event
Hide specific text on load but use same text to identify element for click event

Time:12-03

I want to hide links containing "NOSP" when clicking a No Spoiler button, but also hide that "NOSP" text by default.

Using jQuery this is what I've tried so far:

$("button").click(function(){
$("a:contains('NOSP')").hide();
});

$("a:contains('NOSP')").each(function(){
$(this).text($(this).text().replace('NOSP',''))
});
a { display: table; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button>Hide spoilers</button>

<a href="#">Full match</a>
<a href="#">All goals NOSP</a>
<a href="#">Highlights</a>
<a href="#">Highlights</a>
<a href="#">Highlights NOSP</a>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

(also a jsfiddle)

CodePudding user response:

You can pre-process all this with $(document).ready and add a className to each NOSP link to reference it later, and at the same time remove that string from the link text. Note: just in case there is some word out there with NOSP in it, I broke the text into an array and used array.includes(targ) to find it.

$(document).ready(function() {
      $("a").each(function() {
        let t = $(this).text().split(" ")
        if (t.includes('*')) {
          t.splice(t.indexOf('*'), 1)
          $(this).addClass('nosp').text(t.join(" "))
        }
      })
      $("button").click(function() {
        $("a.nosp").hide();
      });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Hide spoilers</button>

<a href="#">Full match</a>
<a href="#">All goals *</a>
<a href="#">Highlights</a>
<a href="#">Highlights</a>
<a href="#">Highlights *</a>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related