-1
$('ul#test a').click(function(){
 $('this').closest('parent').find('textarea').val(this.getAttribute('href'));   
});

works in Google Chrome snippet but not loaded with Tampermonkey.
I think that it's trying to set a value before even finding the target

(edit) whole script :

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        www.reddit.com/r/some-subreddit
// @grant        none
// ==/UserScript==

(function() {
  'use strict';

  $( "textarea" ).one("click",(function() {
    $(".usertext-edit").prepend ( `
    <div id="gmSomeID"><ul id="gmSomeeID"><a href="#stickers1"</a> <a href="#stickers2"</a> <a href="#stickers3"</a> <a href="#stickers4"</a> <a href="#stickers5"</a ><a href="#stickers6"</a> <a href="#stickers7"</a> <a href="#stickers1"</a> <a href="#stickers2"</a> <a href="#stickers3"</a> <a href="#stickers4"</a> <a href="#stickers5"</a> <a href="#stickers6"</a>
</ul></div>
    ` );
    $('ul#gmSomeeID').css({
      'overflow-y':'scroll',
      'display':'block',
      'overflow-wrap' : 'normal',
      'height':'100px',
      'background-color':'white'
    });

    $('ul#gmSomeeID a').click(function(){
      $("this").closest("div.usertext-edit")
        .find("textarea")
        .val($("this")
        .closest("div.usertext-edit")
        .find("textarea")
        .val() +' '+ '[](' + this.getAttribute('href') + ') ');
    });
  }));
})();  

It displays some pictures above textarea's and I'm trying to make it insert them in the said textarea when they're clicked on

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
a.mtrx
  • 13
  • 1
  • 3

2 Answers2

2

Put your code inside ready function so the event will find the element in your selector since it will be executed just after the full load of the DOM :

$(function(){
   //Your code here
})

Try also the event delegation :

$(function(){
    $('body').on('click', '#test a', function(){
        $(this).closest('parent').find('textarea').val( $(this).attr('href') );
    });  
});

NOTE 1: The code works in the console because the DOM was fully loaded. NOTE 2: The $('this') should be $(this) instead & it will be better to use $(this).attr('href') rather than this.getAttribute('href').

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

When you try the code in the console, the DOM is already done being built. If you have the code as you've shown it, before all of the HTML in the file, it will try to find the elements before the elements have been parsed into memory.

Place your code inside of a document.ready handler:

$(function(){
  $('ul#test a').click(function(){
   $('this').closest('parent').find('textarea').val(this.getAttribute('href')); 
  });
});
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71