如何在某些文本后使用javascript查找元素? [英] how to find element after some text with javascript?
问题描述
我有一个HTML文件,其中包含一些文本(例如'bla-bla'
).我想在此文本节点之后获取一个特定元素(如<a href=...
).
I have a HTML file with some text (like 'bla-bla'
) inside. I want to get a specific element (like <a href=...
) after this text node.
如何使用纯JavaScript或jQuery做到这一点?
How can I do that with pure JavaScript or jQuery?
示例HTML:
<div>
jdlgjalfad dfaldfdalf bla-bla fdfadf afd <br/>
<table>...
<td></td>
</table>
<a href="some_link">here</a>
</div>
推荐答案
$('div:contains('bla-bla')).find('a')
将在您的示例中工作,但可能不适用于您的实际用例. :contains选择器会在其中找到包含一些字符串的div,但是如果需要更多上下文,则可能需要使用正则表达式来查找所需的特定文本:
will work in your example, but may not work for your real use-case. The :contains selector will find a div with some string in it, but you may need to use a regular expression to find the specific text you want if you need more context:
$('div').each(function(){
if (/funky-regex/.test($(this).text())) {
$(this).find('a').doSomethingHere();
}
});
用一个或多个jquery方法替换doSomethingHere().适当的选择取决于您的特定用例.
replacing doSomethingHere() with one or more jquery methods. The appropriate choice will depend on your specific use case.
这篇关于如何在某些文本后使用javascript查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!