根据文本内容查找一个html元素 [英] Finding an html element based on text content

查看:73
本文介绍了根据文本内容查找一个html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

<div>
   <span>TV</span>
</div>

我想通过具有文本'TV'的documentObject来找到此 span ,例如 getElementById 等...类似 getElementByText .我知道可以通过XPath/JQuery/Regex来实现.

I want to find this span through documentObject having text 'TV', like getElementById etc ... something like getElementByText. I know that it's possible through XPath/JQuery/Regex.

但是我只需要通过DOM对象模型即可.因为在我的上下文中只有DOM模型可用.我看到了几个答案:

But I need it to get through DOM object model only. As only DOM model is available in my context. I see couple of answers:

但是这些对我没有帮助,因为我只需要通过DOM模型即可获得

But these are not helpful to me, as I need to get it through DOM model only.

推荐答案

假定文档的格式足以将其解析为正确的DOM对象树,则可以在不使用外部库的情况下遍历整个结构.根据结构,您可能必须检查每个节点才能找到所有匹配项,这可能会很慢.如果您有权访问各种ID,则可以缩小搜索范围并提高性能.

Assuming the document is well-formed enough to parse into a proper DOM object tree, you can iterate through the entire structure without using an external library. Depending on the structure, you may have to examine every node to find all matches, and this may be slow. If you have access to IDs of any sort, you may be able to reduce search scope and improve performance.

您需要的关键属性是每个DOM节点上的 childNodes 集合.从BODY(或其他容器)开始,您可以遍历所有子节点.

The key property you will need is the childNodes collection on every DOM node. Starting with the BODY (or some other container), you can recurse through all the child nodes.

此站点非常简单,但是显示了用于访问DOM元素的无依赖方法.请参阅导航到特定元素的工具"一节.

This site is pretty basic but shows dependency-free methods for accessing DOM elements. See the section called "Tools to Navigate to a Certain Element".

我注意到您提到正则表达式是一种查找元素的方法.正则表达式无法解析整个文档,但是它们在评估单个节点的文本内容(例如部分匹配,模式匹配,大小写不敏感等)时非常有用.正则表达式是JavaScript语言本身的一部分,因此长达十年之久.

I noticed that you mentioned regular expressions as a means to find elements. Regexes are poor for parsing entire documents, but they can be very useful in evaluating the textual content of a single node (e.g. partial matches, pattern matches, case insensitivity, etc.) Regular expressions are part of the JavaScript language itself and have been so for well over a decade.

这篇关于根据文本内容查找一个html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆