tahoma
tahoma

Reputation: 39

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

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>

(also a jsfiddle)

Upvotes: 1

Views: 36

Answers (1)

Kinglish
Kinglish

Reputation: 23664

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>

Upvotes: 1

Related Questions