0

If I write this in my background.js, it's ok:

$("body").append('<p>hello<p/>');

But if I want to write in a specific div of the html I cannot write my element:

$('.re-DetailFeatures').first().before('<p>hello<p/>');

These are my "content_scripts":

    "content_scripts": [ {
        "js": [ "jquery.min.js", "background.js" ],
        "matches": [ "http://*/*", "https://*/*"]
      }],

And the error that ir gives to my: "Uncaught TypeError: $(...).first is not a function"

imj
  • 470
  • 1
  • 8
  • 23
  • 1
    background.js is a name typically used for a background script, which runs in a separate hidden [background page](https://stackoverflow.com/a/10258029) so you may want to use a different content.js script to run in web pages. You say "But if I go to an specific part of the page I cannot write my element" but what exactly do you mean by "go" and "specific part of the page" and "write my element"? Are you doing it in devtools console? Or in a script that you create inside the page DOM? – wOxxOm Mar 31 '19 at 11:58
  • "But if I go to an specific part of the page I cannot write my element"... this is when I want to write in a specific div of the page: $('.re-DetailFeatures').first().before... a div which class is re-DetailFeatures. – imj Mar 31 '19 at 15:58
  • Are you doing it in devtools console? Yes – imj Mar 31 '19 at 15:59
  • Devtools console runs in the page context by default where `$` is not jQuery, but a built-in function of devtools. Click the [context dropdown](https://developers.google.com/web/tools/chrome-devtools/console/#execution-context) in the console toolbar and switch to your extension, then run your commands. – wOxxOm Mar 31 '19 at 16:08

1 Answers1

-2

You need to ensure that jQuery file is called before your script runs. Script tags inside body run before jquery.min.js is loaded because it's called at the end of the document. To solve this you can:

  • Put jQuery in HEAD tag
  • Wrap your script tag inside a document ready event handler. For more info about this, revise this Answer