Jonathan Kittell
Jonathan Kittell

Reputation: 7493

How to find an element by searching with InnerHTML using C# and Selenium

I want to get a particular element id by searching for a matching innerHTML string. For example I want to find the element id that has the innerHTML "Start of Car".

enter image description here

public static bool SelectSomething(IWebDriver driver, string searchName)
{
    var js = driver as IJavaScriptExecutor;
    if (js == null) return false;
    var element = (string) js.ExecuteScript("...script to get the ids...");
    var x = driver.FindElement(By.Id(element));
    x.Click();
    return true;
}

I know it is possible to loop through and find all of the innerHTML using JavaScript but how do you return the id once you find innerHTML that matches the 'searchName' string?

Upvotes: 0

Views: 1392

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34416

Using jQuery it is simple, just use :contains - https://api.jquery.com/contains-selector/

http://jsfiddle.net/jayblanchard/5UvFE/

var found = $("td:contains('Start of Car')").attr('id');

This allows you to return the ID of the element in question.

Alternatively here is a way to do it with just JavaScript -

function textID(node, text) {
    if (node.nodeValue == text) {
        return node.parentNode;
    }

    for (var i = 0; i < node.childNodes.length; i++) {
        var returnValue = textID(node.childNodes[i], text);
        if (returnValue != null) {
            return returnValue;
        }
    }

    return null;
}

http://jsfiddle.net/jayblanchard/5UvFE/1/

Upvotes: 2

Related Questions