Search code examples
javascriptplaywright

How would I rewrite this javascript command in playwright? document.getElementsByClassName(parent)[i].querySelector(child)


I have this command in javascript that works, but can't seem to translate it into playwright. For my project, I have 10 item cards and I need to find if item description is missing inside each item card or not. (there should be 1 missing description in my case)

document.getElementsByClassName(itemCard)[i].querySelector(itemDescription)

I've tried

const rows = await this.page.locator(itemCard); 
 inside loop)
 if (await rows.locator('has:itemDescription').nth(i) == null) { 
        console.log("No description") } 
 else { console.log("has description"} 

but the above code seems to print out 10 "has descriptions" instead of 9. There should be one "No description".


Solution

  • To do an almost exact translation of what you seemed to be doing, your if condition could translate to this:

    if (!(await rows.nth(i).locator(itemDescription).isVisible())) {
    

    I don’t know the full context/goal or what your actual core requirement is, but if it satisfies it, you could also just get a count of how many exist, and assert or log how many there are. To get this count, you could do something like this:

    await rows.filter({ has: this.page.locator(itemDescription) }).count();
    

    Also just realized that you were doing get by class name before, so your rows locator also would need a tweak to specify css class, like so:

    const rows = await this.page.locator(`.${itemCard}`);
    

    Happy to provide more specifics if needed and given more context. Hope that helps!