简体   繁体   中英

Remove web element from the IList <IWebElement> using C# in Selenium

I'm actually trying to remove the element from IList if certain condition occurs, but seems like I'm getting the same list .Count number. Below is my code:

    [FindsBy(How = How.XPath, Using = "//button[@aria-label='delete']")]
    private IList <IWebElement> _deleteIcons;

******** SOME CODE HERE **********

    for (var i = 0; i<_deleteIcons.Count; i++)
                {
                    if (_deleteIcons[i].GetAttribute("disabled").Contains("true"))
                    {
                        _deleteIcons.RemoveAt(i);
                    }
                }
    Debug.WriteLine(_deleteIcons.Count);

Imagine there are 6 total elements in the IList, and 2 of them contain "disabled" =="true" At the end I would like to write to debug console the variable count and see 4 . Currently once the piece of code is run, I still get the same amount of 6 elements in IList.

The easiest way to do this is to use a CSS selector and just select those buttons that are not disabled. It will be faster and you won't need to filter afterwards.

"button[aria-label='delete']:not([disabled])"

This is what you need to do before your for loop

_deleteIcons = [CODE_TO_GET_ELEMENETS].ToList()

Then this should work

or you can use Linq to achieve this without the need for this loop:

_deleteIcons = [CODE_TO_GET_ELEMENETS].Where(x => x.GetAttribute("disabled").Contains("true"))

I had a similar situation occur where I used a LINQ query to rebuild the list I was making. System.NotSupportedException: 'Collection is read-only.' thrown when removing object from iList

I know you've had an answer already but just putting this out there too.

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