Diego Slinger
Diego Slinger

Reputation: 149

Selenium. Find element by class and remove it from DOM using JS

The code that worked for me well. I get the quantity of messages first and then remove it.

    public static void RemoveMSGs()
    {
        // Remove messages from DOM using JS
        int MessagesOnThePage = Program.ChromeDriver.FindElementsByClassName("GLS-JUXDKAD").Count;
        Console.WriteLine("Total messages: " + MessagesOnThePage);

        while (MessagesOnThePage != 0)
        {
            MessagesOnThePage--;
            {
                try
                {
                    Program.js.ExecuteScript("var ele = document.querySelector('.GLS-JUXDKAD'); ele.parentNode.removeChild(ele); "); // This code removes the whole message
                    Console.WriteLine("JS execution command: remove message on the page. Total messages on the page: " + MessagesOnThePage);
                }
                catch
                {
                    Console.WriteLine("JS error. Can't remove message on the page. There is no more messages. Total messages: " + MessagesOnThePage);
                }
            }
        }
    }

Upvotes: 0

Views: 659

Answers (1)

gurvinder372
gurvinder372

Reputation: 68383

Just wrap the following lines in your selenium code

var ele = document.querySelector('GLS-JUXDFAD');
ele.parentNode.removeChild( ele );

Upvotes: 2

Related Questions