Search code examples
javascriptjqueryselectortagname

jQuery 1.9.1 selection by tag name returns only the first element


I'm developing an userscript for Greasemonkey/Tampermonkey that removes the onmousedown attribute from tags in Google search results pages.

The plugin indicates that the script is running, the script is executed, but nothing happen.

I've opened the console and tried to do it manually, but the selector selects only the first in the page.

I've tried with:

$("a")
$("a.l")
$(".l")

I've also tried to change the position of the userscript at document-start, document-body and document-end, but the result is the same: only the first element that matches is returned.

Script code:

// ==UserScript==
// @name       Google onmousedown remove
// @version    0.1
// @include      /^https?://[a-z]*\.?google\.[a-z\.]+/search.*/
// @require http://code.jquery.com/jquery-1.9.1.min.js
// @run-at     document-end
// ==/UserScript==

$(document).ready(function (){
    $("a.l").each(function (){ $(this).removeAttr("onmousedown"); });
});

Where's the problem? Thanks.


Solution

  • If you try to type $ in console being on search page you will see something different from usual function (e,t){return new i.fn.init(e,t,u)} that is defined by jQuery. So...

    Seems like Google defines its own $ function and it behaves differently. The simplest solution would be to use jQuery explicitly instead of $: jQuery('a.l').

    But it is to long so here is the trick from the jQuery for it: instead of document.ready, invoke jQuery function and pass it the function with argument $. Then inside this function $ equals jQuery.

    jQuery(function ($){
        $("a.l").each(function (){ $(this).removeAttr("onmousedown"); });
    });
    

    Not tested, but should work.