Use Selenium to Find Elements By Knockout’s Data-bind

I created a quick C# extension method for Selenium to find an element by its data-bind attribute. I wanted to find an element by the binding instead of having to add a class or id to the element.

If you have a Knockout Model

function MyViewModel { “use strict”; this.name = ko.observable; }

In the html the element may look like this

<input id="nameInput" data-bind="text: name" />

With the extension method I can call:

public class MappedPage { public string GetName { var container= Browser.Driver.FindElement(By.Id("infoContainer"));

// call the extension method return container.FindElementByDataBind("name").Text; }

public void SetName(string name) { //... assume code to set the text box... } }

// in a test method var page = new MappedPage; page.SetName("Kevin"); Assert.AreEqual("Kevin", page.GetName;, "Name should match what I put in the text box");

Here’s the extension method in a static class. Don’t forget to add the using statement to this class to be able to find the method (Resharper helps you find it if you have Resharper)

public static WebElementExtensions { ///

/// Find the element by data bind property. /// ex: (data-bind='text: name'). /// /// /// The container element. /// /// /// The data bind property. /// /// /// The binding after data-bind=. For example text /// /// /// The . /// public static IWebElement FindElementByDataBind(this IWebElement element, string dataBindProperty, string binding = "text") { return element.FindElement(By.CssSelector(string.Format("[data-bind*='{0}: {1}']", binding, dataBindProperty))); } }

Update: the above only works if the the data-bind matches exactly. Changing to data-bind*=’{0}: {1}’] changes the search with contains.

This article is part of the GWB Archives. Original Author: Aligned

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.