【发布时间】:2011-06-19 17:14:46
【问题描述】:
示例文本
我想通过使用文本值来获取 html 页面中特定字符串的 id 或类,在本例中为 “示例文本”。有什么办法吗?
【问题讨论】:
-
什么是包装器?您是否在 DOM 中搜索父元素?
标签: javascript string tags
示例文本
我想通过使用文本值来获取 html 页面中特定字符串的 id 或类,在本例中为 “示例文本”。有什么办法吗?
【问题讨论】:
标签: javascript string tags
使用jQuery,很简单:
var searchText = 'Sample text',
$element = $('span:contains(' + searchText ')'),
id = $element.attr('id'),
className = $element.attr('class');
对于严格的普通 JS,它并不那么简洁。
var spans = document.getElementsByTagName('span'),
element,
text,
re = /Sample Text/,
// IE doesn't support textContent, FF doesn't support innerText
prop = document.body.innerText ? 'innerText' : 'textContent';
for (var i=0; i<spans.length; i++)
{
if (re.test(spans[i][prop]))
{
span = spans[i];
break;
}
}
var id, className;
if (span)
{
id = span.id;
className = span.className;
}
【讨论】: