Search code examples
jqueryforum

jQuery to hide specific comments from forums


So, I'm learning some jQuery and I've decided to use as a training ground a request a friend made me. I'm trying to create a script for greasemonkey that when a selected user posts something in a thread on the Overwatch forums: (https://us.forums.blizzard.com/en/overwatch/c/general-discussion) it hides that specific comment from the entire thread.

The forum in question identifies the users by a tag called: data-user-id="XXXX" which is what I want to use as a target of my script while selecting which posts to hide

The expected behaviour is that when the script runs and finds that a certain user by the user ID I've provided has written something it will just hide its entire post in the thread I'm currently reading.

These are some of the experiments I made:

//Experiment 1
$('#post_2:contains("data-user-id="XXXX"")').remove();

//Experiment 2
$('.boxed.onscreen-post:contains("XXXX")').remove();

//Experiment 3
$("#post_2 > .boxed.onscreen-post:contains('XXXX')").remove();

I'm struggling a bit with the concept of dynamic IDs to target the element in question and to make it read the content of the div to find the ID of the user.

These queries really didn't give me any error so my guess is that they couldn't find the string of text required to act.


Solution

  • I think you just need this:

    $('[data-user-id="XXXX"]').remove();
    

    If you want to use the css :contains(), drop the string quotes. According to the W3Schools jQuery :contains() Selector you just need to put the string without quotes in the :contains() selector. This will look for text between the start and end tag of the element .onscreen-post. So not in its attributes but in the real content of the block.

    $('.boxed.onscreen-post:contains(XXXX)').remove();
    
    // Or when it is a variable
    var searchFor = 'XXXX';
    $('.boxed.onscreen-post:contains(' + searchFor + ')').remove();
    

    The above doesn't work for html attributes like your data-user-id="XXXX". If you want the behaviour of the :contains() selector on a html attr which is not an exact match you need the *= in the selector like this:

    $('[data-user-id*="XXXX"]').remove();
    
    // Or when it is a variable
    var searchFor = 'XXXX';
    $('[data-user-id*="' + searchFor + '"]').remove();