Search for html element based on text content

I have html code like

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

I want to find this span via documentObject with the text "TV", for example getElementById etc., something like getElementByText . I know this is possible through XPath / JQuery / Regex.

But I need it to go through the DOM object model. Since in my context only the DOM model is available. I see a couple of answers:

But this is not useful to me, since I need to get it only using the DOM model.

+4
source share
2 answers

Assuming the document is well-formed enough to parse the correct tree of DOM objects, you can iterate through the entire structure without using an external library. Depending on the structure, you may need to examine each node to find all matches, and this may be slow. If you have access to any type of identifier, you can reduce the search scope and improve performance.

The key property you'll need is the childNodes collection on each DOM node. Starting with BODY (or another container), you can rewrite all child nodes.

This site is pretty simple, but shows dependency-free methods for accessing DOM elements. See the section β€œTools for navigating to a specific item”.

I noticed that you mentioned regular expressions as a means of finding elements. Regular expressions are part of the JavaScript language and can be very useful when evaluating the text content of a single node (for example, partial matches, pattern matches, case insensitive, etc.). Regular expressions are part of the JavaScript language and have been like this for more than a decade.

+2
source

The only thing I can think of is something like this:

 function getElementByTextContent(text) { var spanList = document.getElementsByTagName("span"); for (var i = 0, len = spanList.length; i < len; i++) { if(spanList[i].textContent === text) // use .innerHTML if you need IE compatibility return spanList[i] } } 

Of course, it is assumed that you are only looking for <span> elements, but this might work for you. There is also a demo here:

http://jsfiddle.net/uATdG/

0
source

Source: https://habr.com/ru/post/1387512/


All Articles