如何根据其包含的字符串获取元素ID?
<span id="th67">This the string I need to match</span>
Run Code Online (Sandbox Code Playgroud)
我无法使用JQuery或任何其他Javascript库来执行此操作.
我需要这样做进行硒测试.
没有我的图书馆,我没有意识到我在JS中是多么无用!
谢谢大家的帮助.
如果您要定位的浏览器支持XPath,则可以执行简单的XPath查询:
// 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();
}
Run Code Online (Sandbox Code Playgroud)
然后跑吧
var myElement = getElementByText( "This is the string I need to match" );
if ( myElement )
{
// do something with myElement.id
}
Run Code Online (Sandbox Code Playgroud)
好吧,如果你知道你正在寻找什么样的标签,你可以这样做:
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 ...
}
Run Code Online (Sandbox Code Playgroud)
如果你想得到想象,你可以构建一个xpath查询.