Get Collection of TextNode Objects
While getElementsByTagName() efficiently retrieves element objects, it's ineffective for textNode objects as they aren't elements. Hence, the question arises: is there an alternative method to acquire all textNode objects within a document?
Alternative Methods
Although walking the DOM is a viable option, the lack of a browser-native approach seems peculiar. To address this, several methods have emerged:
Performance Comparison
Performance tests have been conducted over 1000 runs to compare these methods. While getElementsByTagName stands out as the fastest, it resorts to selecting specific element tags and might not capture all text nodes.
Interestingly, TreeWalker performs nearly identically to getElementsByTagName and is arguably comparable in speed to the more elaborate DOM traversing methods. This highlights the efficiency of TreeWalker for retrieving text nodes.
The above is the detailed content of How to Efficiently Get All TextNode Objects in a Document?. For more information, please follow other related articles on the PHP Chinese website!