4

How can I get an elemnts ID based on the string it contains?

<span id="th67">This the string I need to match</span>

I can't make use of JQuery or any other Javascript library to do this.

I need to do this for a selenium test.

I didn't realise how useless I am in JS without my libraries!

Thanks all for any help.

3 Answers 3

7

Well, if you know what kind of tag you're looking for, you can just do:

var spans = document.getElementsByTagName('span'), targetId;
for (var i = 0; i < spans.length; ++i) {
  if (spans[i].innerText === stringToMatch) {
    // found it ...
    targetId = spans[i].id;
    break;
  }
}
if (targetId) {
  // ... do whatever ...
}

If you want to get fancy you could construct an xpath query, I guess.

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

Comments

7

If the browsers you're targeting support XPath you can do a simple XPath query:

// Find an element by the text it contains, optionally
// starting at specified parent element.
function getElementByText( text, ctx)
{
  return document.evaluate("//*[.='"+text+"']", 
     ctx || document, null, XPathResult.ANY_TYPE, null).iterateNext();
}

Then just run

var myElement = getElementByText( "This is the string I need to match" );
if ( myElement )
{
  // do something with myElement.id
}

1 Comment

That's elegant. Any way I can get all elements containing a string? I tried while (myElement = getElementByText(searchString)), but it seems to generate an endless loop.
3

Here's a simple recursive function that will do it:

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

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

    return null;
}

Use it as:

var target = findByText(document, "This the string I need to match");

This will end up with either target being null, or it being a DOM node whose id you can get with target.id.

See it in action.

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.