最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get Element ID by String it Contains using Plain Javascript - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Apr 24, 2011 at 14:51 KayKay 8457 gold badges21 silver badges33 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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.

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
}

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.

发布评论

评论列表(0)

  1. 暂无评论