'How can I test jQuery code in the browser console?

I want to test if my jQuery code is sound. So I thought I just enter the code in the browser console. I use Mozilla Firefox.

I want to test if I can select ids and that stuff.

But when I enter:

$("#testId")

I get the following error:

Uncaught SyntaxError: private names aren't valid in this context

Are the elements that I want to access private? What does that mean and why is that?



Solution 1:[1]

follow these steps to test & practice JQuery in your console: first, use the browser debugger tool to inspect any element in your browser, view the source code, e.g like classNames and id'

Next, now use the jQuery syntax to select it example $(".className") or $("#ids"),

Solution 2:[2]

just type

console.log($("#testId"));

Solution 3:[3]

Try something like this

<div id="testId">hi user1664377</div>

then

console.log($("#testId").text()); // you will see "hi user1664377" in console

Solution 4:[4]

In case you dont have access to jQuery in console (window/document).

You can add the jQuery script to DOM directly from console by creating and appending the script to body:

let s = document.createElement('script')
s.setAttribute('src','https://code.jquery.com/jquery-3.6.0.min.js')
document.getElementsByTagName('body')[0].appendChild(s)

And now eg get the jQuery version:

console.log(jQuery.fn.jquery)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abdulkareem alabi
Solution 2 Krishna Jonnalagadda
Solution 3 Joukhar
Solution 4 Fappie.