简体   繁体   中英

How to iterate through a list of JSON elements and access their attributes using webdriverio?

[Using Chimp.js – Synchronous style webdriverio API]

How can I properly iterate through my array of elements? Or, more specifically, how do I access the attributes of the elements themselves? I'm confused as to the .elements() function found in the API and how to extract the elements themselves from there.

var myItem;
var elemArray = browser.elements('.castMemberPicture').value;
console.log(elemArray);

for (myItem in elemArray){ 
    console.log("myItem: " + myItem);
    //  I can log the JSON obj IDs successfully, but can’t seem to access elements like clientHeight, alt, ...
};

How do I access the attributes?

(output)

[ { ELEMENT: '0' },
  { ELEMENT: '1' },
  { ELEMENT: '2' },
  { ELEMENT: '3' }]
myItem: 0
myItem: 1
myItem: 2
myItem: 3

... calling to .ELEMENT gives undefined calls, so it's likely my use of the API / syntax.

I saw https://github.com/webdriverio/webdriverio/issues/273 but I can't get to access the attributes no matter what combination of .ELEMENT .value and function I try. Help?

note - if I try to explore the elements themselves by printing using console.log("myItem: " + JSON.stringify(elemArray[myItem].ELEMENT)); the output becomes

[ { ELEMENT: '0' },
  { ELEMENT: '1' },
  { ELEMENT: '2' },
  { ELEMENT: '3' }]
myItem: "0"
myItem: "1"
myItem: "2"
myItem: "3"

Here's the way to traverse it and check the elements in Chimp:

var myItem;
var elemArray = browser.elements('.castMemberPicture').value;
console.log(elemArray);

// the following will traverse the array and print out the elements 'alt' Attribute!
for (myItem in elemArray){ 
    console.log( browser.elementIdAttribute(myItem, 'alt').value);
};

According to the docs for 'elements', you can access each element individually using the element command:

The array of elements can be retrieved using the 'response.value' which is a collection of element ID's and can be accessed in the subsequent commands using the '.ELEMENT' method.

So for your loop:

var myItem;
var elemArray = browser.elements('.castMemberPicture').value;

for (myItem in elemArray){ 
    console.log( browser.getAttribute(myItem, 'alt'));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM