Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Greasemonkey and Jquery to hide an HTML element with a certain class?

This news site (The Guardian) has a small frame that displays in the bottom-right of the page, with code like this:

<div class="initially-off social-cta-overlay">

    <div class="social-cta-overlay-content"></div>

</div>

I hid the internal contents of the inner div because they're not important. I wrote a Greasemonkey script that uses JQuery to hide this box because it appears on every page:

// ==UserScript==
// @name        hide-guardian-ad
// @namespace   guardian
// @description Hides the Guardian social media frame
// @version     1
// @grant       none
// ==/UserScript==

// @require       http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js

$(".social-cta-overlay").hide()

I installed the script, but nothing happens and the box is still there.

like image 357
Jacob Avatar asked Feb 25 '14 16:02

Jacob


People also ask

How do I hide certain elements in HTML?

To hide an element, set the style display property to “none”. document. getElementById("element"). style.

Can we hide HTML elements using Javascript?

Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.

What is the correct jQuery code to hide all elements with ID?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.


1 Answers

That script has 3 problems (worst first):

  1. The @require directive is outside the metadata block. This means that Greasemonkey ignores it as just an ordinary javascript comment.
  2. There is no @include or @match directive. This means that the script will fire on every page and iframe of every site! (Crashing some of them, and chewing up resources.)
  3. @grant none means that the script will interfere with and crash all or part of many sites.

This script works:

// ==UserScript==
// @name        hide-guardian-ad
// @include     http://www.theguardian.com/*
// @description Hides the Guardian social media frame
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant       GM_addStyle
// ==/UserScript==

$(".social-cta-overlay").hide()
like image 97
Brock Adams Avatar answered Oct 16 '22 08:10

Brock Adams