How can I test jQuery code in the browser console? - javascript

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?

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"),

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

Try something like this
<div id="testId">hi user1664377</div>
then
console.log($("#testId").text()); // you will see "hi user1664377" in console

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)

Related

Need to pass argument in href method

I am working on a web application to show some data graphically using spring framework. In my code I am trying to call a javascript method from href tag of html. Problem is i can't pass argument to that method.
my html snippet is as below where i call the method.
and javascript method as follow
function getLimitHistory(opcode){
console.log("Getting limit history for opcode: "+opcode);
}
Note that limitData.operatorCode is a thymeleaf variable and it has value 'S47648' that i want to pass as argument to the method. But when press on that href item i am getting some error saying
Uncaught SyntaxError: missing ) after argument list VM382:1
I hope somebody will help me here.
I wonder why nobody in the internet faced this problem before.
try using
<a th:href="javascript:getLimitHistory(${limitData.operatorCode})"
th:text="${limitData.operatorCode}"></a>
Need to use th:* prefix. Once templates are compiled, all th:* tags will be disappeared.
Docs:
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart

WebdriverIO - How can I retrieve the HTML of the currently focused/selected/active element?

I am looking to retrieve a focused element's HTML. Looking at the webdriver.io documentation, the method .getActiveElement() is supposed to do the trick. However, my IDE (WebStorm) shows an error stating that it is an "unresolved function or method" (the method isn't recognized). I've also seen someone mention the method .elementActive(), however this method shows up unrecognized as well.
Help! How can I retrieve the HTML of the current focused element?
If you're using WebdriverIO v5, you should be able to run the following:
const activeElement = $(function () { return document.activeElement });
const html = activeElement.getHTML();
console.log(html);
https://webdriver.io/docs/selectors.html#js-function

Python 3 Selenium fails to execute javascript

I'm using python 3 and I'm using Selenium to try to scrape data off a website. I need to remove a class from a list item in order to display the data I need, this is the code:
driver.execute_script("document.getElementsByClassName('otherClassName isSelected').classList.remove('isSelected');")
but I get the error
"selenium.common.exceptions.WebDriverException: Message: unknown error:
Cannot read property 'remove' of undefined"
I have also tried
driver.execute_script("document.getElementsByClassName('otherClassName isSelected').setAttribute('class', 'otherClassName')")
but then I get
selenium.common.exceptions.WebDriverException: Message: unknown error: document.getElementsByClassName(...).setAttribute is not a function
I guess this is because you're trying to apply class name update for multiple elements at once while setAttribute() allows to apply changes to one element at the time.
Try below code instead
js = """document.querySelectorAll('.otherClassName.isSelected')
.forEach( x=> x.setAttribute("class","otherClassName"));"""
driver.execute_script(js)
P.S. It seem to be XY problem as usually you don't need to make changes to page source while page scraping. You should share more details about your initial problem
I had forgotten to add [0] after getting the element by class, so the correct code should be:
driver.execute_script("document.getElementsByClassName('otherClassName isSelected')[0].classList.remove('isSelected');")

Kony Reference Error :- Can't find variable: testCall

In my code i have a simple drop down, on select of which i am calling a function called testCall() , But for some reason i am seeing a reference error :- cant find variable: testCall , Can any one please help
code below
function testCall(){
//print statements
//kony.print("test");
}
screen shots
if there is any error in your function of the entire js file, such errors appear, in my case i had a single equals in a if condition which was the issue.
it seems like your .js (module) contains some java-script error (most probably syntax error). Better you can copy all the java-script code and put it in chrome console it will show you the syntax error.

Handle "is not a function" error in jquery

I like to display a custom message to user when jquery plugin required is not loaded on page.
For example to use jshowoff plugin (http://ekallevig.com/jshowoff/) its mandatory to include
jquery.jshowoff.min.js
However I would like to put some code to initially check if jquery.jshowff.min.js is already loaded on the page or not.
And if not loaded, display error message saying that required plugin is not available rather than error is browser console as $.jshowoff is not a function.
Could someone advice on how to implement this please ?
Thank you very much for your help.
If you use the plugin via a jQuery object, e.g.:
$(/*...stuff here...*/).somePlugin();
...then you can test whether it's loaded like this:
if (!$.fn.somePlugin) {
// somePlugin is not loaded for some reason
}
If you use it directly from jQuery ($), e.g:
$.somePlugin();
...then you can test for that like this:
if (!$.somePlugin) {
// somePlugin is not loaded for some reason
}

Categories