1

I'm trying to highlight all the elements of a page, using Selenium to inject some JavaScript and CSS.

However when I run my test i'm only getting back errors complaining that it can't find the elements.

'javascript error: $ is not defined

The page i'm using is:

https://statsroyale.com/decks/popular and i'm trying to highlight each of the cards in a deck.

The selector that i'm using is:

public IList<IWebElement> AllCardsInPopularDecks => Driver.FindElements(By.XPath("//*[@class='popularDecks__decklist']//img"));

And my JavaScript method is:

internal void HighlightElement(IWebElement element)
        {
            var jsDriver = (IJavaScriptExecutor)Driver;
            string highlightJavascript = @"$(arguments[0]).css({ ""border-width"" : ""2px"", ""border-style"" : ""solid"", ""border-color"" : ""red"", ""background"" : ""yellow"" });";
            jsDriver.ExecuteScript(highlightJavascript, new object[] { element });
        }

My method which is calling the test that is:

public void HighlightAllCards()
        {
            foreach (var card in Map.AllCardsInPopularDecks)
            {
                HighlightElement(card);
            }
        }

And my test case is:

[TestMethod]
        public void TestOne()
        {
            Homepage.GoTo();
            Homepage.GoToPopularDecks();
            Homepage.HighlightAllCards();
        }

(This only a test... so ignore the name!)

I've tried to debug the issue and it seems that a element is being found. But it's not being passed to my JS method.

2

1 Answer 1

2

$() is a jQuery selector, your page does not load jQuery. You need to find another way to access and interact with the element and JavaScript.

You can also change CSS with VanillaJS, which is supported by most browsers by default: https://gomakethings.com/two-ways-to-set-an-elements-css-with-vanilla-javascript/

Code with VanillaJS would look something like this:

internal void HighlightElement(IWebElement element)
        {
            var jsDriver = (IJavaScriptExecutor)Driver;
            string highlightJavascript = @"arguments[0].style.backgroundColor='yellow');";
            jsDriver.ExecuteScript(highlightJavascript, element);
        }

You could inject jQuery, but you have the risk of breaking other JavaScript on the web-page: https://medium.com/virtualmind-io/jquery-injection-for-selenium-automation-tests-f6121ea57993

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.