Clicking an element inside element handle - javascript

How can an element inside of existing handle be clicked?
Considering that there's a reference to foo handle:
const fooHandle = await page.$('.foo');
Currently foo selector is repeated:
page.click('.foo .bar');
I'd like to select .bar based on fooHandle reference instead of repeating .foo selector. In other places obtaining a handle with nested elements involves more complex checks that cannot be done with simple selector.
I'm using Playwright but I assume the solution is the same as for Puppeteer due to API similarity.

In Playwright, $ and $$ methods are available on ElementHandle objects too:
elementHandle.$(selector)
selector <string> - A selector to query for.
returns: <Promise<null|ElementHandle>>
The method finds an element matching the
specified selector in the ElementHandle's subtree. [...]
If no elements match the selector, returns null.
So your code can be organized like this:
const fooHandle = await page.$('.foo');
const barHandle = await fooHandle.$('.bar');
await barHandle.click();

Related

addEventListener function not working in javascript

I am trying to check if a function that is meant to be triggered by a click with a console.log but the console message never comes up
<script src="e-com.js" async></script>
this is how i linked the js file in the head
Remove
this is the link I want the event on
let removeItem=document.getElementById("remove")
for (i=0; i<removeItem.length; i++){
let remove = removeItem.addEventListener("click", function(){
console.log("Clicked");
})
}
This is the js function
The issue seems to be that you are trying to loop over the result of getElementById(), which doesn't return an iterable.
To fix it, you just need to remove the loop. The code below should work correctly^.
const removeItem = document.getElementById("remove");
removeItem.addEventListener("click", () => {
console.log("Clicked!");
});
Remove
According to MDN Web Docs:
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.
As it states, getElementById() returns an Element, which is just an object, in short. This is why you cannot iterate over it.
If you wanted to listen to multiple objects with a for loop, you need to change a few things.
First, you can't use an id, as the id attribute is unique, and can only be used once in a HTML document. Therefore, to get multiple elements, you need to use the class attribute. See an example of the class attribute in use below.
<div class="division">Division!</div>
The class attribute can be used by any HTML element.
So, to get all of the classes and iterate over them, you need to use either the getElementsByClassName() method, or the querySelectorAll() method.
The only difference between the two is that getElementsByClassName() returns a live HTMLCollection, while querySelectorAll() returns a static HTMLCollection.
If you were to use querySelectorAll(), your code would look like this^.
const removeItem = document.querySelectorAll("remove");
Array.from(removeItem).forEach((ele) => {
ele.addEventListener("click", () => {
console.log("Clicked!");
});
});
Remove
Remove
Remove
Both of these solutions should work correctly, but they depend on what you need to accomplish.
^ The code has been modified slightly.
.getElementById() doesn't return an array since you're not allowed to have more than one element with a single id.
Therefore, the for loop failed.
Try
let removeItem=document.getElementById("remove")
removeItem.addEventListener("click", function(){
console.log("Clicked");
})

Return array with CSS query in Puppeteer

I am trying to get an array of strings from a website with puppeteer.
I have the CSS Selector td[class*="myClass"] which selects all the elements I want, and I then want to get the .innerText of every one of them.
So with that selector I know I can select 20 elements (I have tested this with <style> td[class*="myClass"] {background: red}</style>).
I am trying to get an array of their .innerText with:
console.log(await page.$eval('td[class*="myClass"]', element => element.innerText));
however this returns only the first element.
Does anyone know how I can select all the 20 elements and not only the first one?
Thank you!
await page.$$eval('td[class*="good_to_col"]', element => element.innerText);
An array doesn't have innerText property. If you want to return an array of 20 innerTexts, you need to map it:
await page.$$eval('td[class*="good_to_col"]', elements => elements.map(
element => element.innerText)
);
It's mentioned in the docs.
For convenience/semantic reasons, Puppeteer provides you with two different eval functions.
page.$eval() runs document.querySelector and, thus, only passes the first element it finds to your pageFunction.
page.$$eval() internally runs document.querySelectorAll and, thus, passes multiple elements to your pageFunction and returns an array.
A word of caution:
Some people may wrongfully assume, the second argument passed to $$eval is an iterator function that is invoked for each result of the css-selector. However, a bit counter-intuitively, $$eval passes an array as argument to your function, so any mapping needs to be done on this array. So referring to the OP, instead of page.$$eval('td[class*="good_to_col"]', element => element.innerText) use page.$$eval('td[class*="good_to_col"]', elements => elements.map(e => e.innerText)) and it shall work.

Piece of jQuery code to enable class selector?

I am not using jQuery, but I have one line of code that enables the $ selector shortcut, as follows:
let $ = function (id) { return document.getElementById(id); }
I would like to also add whatever code necessary so that I can use the class selector shortcut as well.
Right now I have this:
let $c = function (cl) { return document.getElementsByClassName(cl); }
And I can select elements by class with $c("some-class"), but that returns a list that I need to then cycle through.
I would like to be able to use stuff like $(".some-class").remove("some-class") - to remove the class from all elements that have it without having to have a loop cycle through the list and remove them one by one.
Could anyone point me toward the part of jQuery that does that so I can include it and not the entire library?
I tried looking through the jQuery code for the term className but there are 39 instances and I'm not sure which part I need.
The closest thing native JS has to jQuery's sizzle selector engine is querySelector() or querySelectorAll(), depending on whether you're expecting a single element to be found, or multiple.
In your example, this would be:
let $ = selector => document.querySelectorAll(selector);

How to find descendant elements of a selected element or ElementHandle?

In other browser automation frameworks there tends to be a "find" method that allows the user to find all decedents of a given element that match the selector for example:
https://www.w3schools.com/jquery/jquery_traversing_descendants.asp
$(document).ready(function(){
$("div").find("span");
});
The above method returns all elements that match span descending from the given div.
If I have an ElementHandle, is there a way I could find all dependents that match a given selector using puppeteer?
Yes, you can use the elementHandle.$ function. Quote from the docs:
The method runs element.querySelector within the page. If no element matches the selector, the return value resolves to null.
Code sample:
const elementHandle = await page.$('div');
const elementInsideHandle = await elementHandle.$('span');
If you want to query multiple elements, there is also the $$ function to run element.querySelectorAll inside the page.

Puppeteer - using querySelectorAll() to access elements in a dynamic HTML environment

Searching the documentation for querySelectorAll() i got this:
A NodeList object, representing all elements in the document that
matches the specified CSS selector(s). The NodeList is a static
collection, meaning that changes in the DOM has NO effect in the
collection. Throws a SYNTAX_ERR exception if the selector(s) is
invalid.
What if you delete some elements. Then new elements appear (with the same class name as the old ones) due to dynamic html.
But now you want to access the new ones.
Will i be able to rerun the querySelectorAll()? Or the old elements will be in the array?
You will of course be able to rerun querySelectorAll() and each time it will return the elements currently corresponding to the query — the important thing is you will have to rerun it to get new elements.
An example:
(async() => {
// ... usual create browser and page stuff
var items = [];
while(items = await page.$$eval('p', pp => pp.map( p => p.textContent ) ))
{
console.log(items);
await page.waitFor(1000);
}
})()
page.$$eval runs Array.from(document.querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction.
The result:
Events can only be put on to existing Elements, and don't exist when the Elements don't, so you have to assign Events to the Elements after you make them. A good solution to avoid the reassignment, is to use jQuery's .on(). Either that, or make a function that you just run again.

Categories