0

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?

2
  • Why does a simple .Text not work? Commented Apr 22, 2014 at 10:26
  • I haven't considered that...where would .Text go? Commented Apr 22, 2014 at 21:34

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.