Find Element Containing Specific Text with Vanilla JS

Find Element Containing Specific Text with Vanilla JS

vlogize

55 лет назад

0 Просмотров

Learn how to efficiently search for HTML elements that contain specific text using vanilla JavaScript, avoiding parent elements in the process.
---
This video is based on the question https://stackoverflow.com/q/73467761/ asked by the user 'potato' ( https://stackoverflow.com/u/17395794/ ) and on the answer https://stackoverflow.com/a/73467862/ provided by the user 'connexo' ( https://stackoverflow.com/u/3744304/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Find element containing specific text with vanilla js

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/licensing
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/by-sa/4.0/ ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/by-sa/4.0/ ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Finding Elements with Specific Text in Vanilla JavaScript

JavaScript is a powerful tool for web development, yet many developers find themselves looking for functionality that simplifies their tasks. One common problem arises when trying to locate HTML elements containing specific text. While jQuery has a convenient method for this with $( ':contains(text)' ), you might wonder how to achieve the same result using only vanilla JavaScript.

In this guide, we will explore a solution for finding elements that contain specific text, while ensuring we exclude parent elements. Let's dive into the problem and outline a concise solution.

The Problem

You may need to locate elements in your HTML document that contain a specific string of text. For instance, if you want to find a span or div that holds the word "foo," you don't want to inadvertently capture any parent elements—only the direct one that wraps the text.

The Solution

Step-by-Step Breakdown

To implement our solution, we will create a JavaScript function that searches through all child nodes. The function will check each node's text content to find our desired string. Here's how we can achieve that:

Define the Search String: Set the string you are looking for.

Implement the Function: Write a function that:

Takes a needle (the text to search for) and a haystack (the starting parent to search within).

Uses querySelectorAll to get all elements and then checks their child nodes.

Only returns the parent of any text node that matches the search string and ignores any script tags.

The Code

Here’s the complete JavaScript implementation:

[[See Video to Reveal this Text or Code Snippet]]

How It Works:

const searchString = 'foo';: This line initializes the string we are searching for.

function findByText(needle, haystack = document): We define our function, where needle is the text we're looking for, and haystack is the HTML document or a specific element to start searching within.

[...haystack.querySelectorAll('*')]: We convert the NodeList of all elements into an array to be processed using reduce.

Text Node Check: It carefully checks if the node type is text (nodeType === 3) and if the text includes the needle.

Collecting Parent Elements: If a match is found, it collects the parent element of that text node.

This function outputs an array of elements that directly wrap the text you are searching for.

Conclusion

Using vanilla JavaScript to find elements containing specific text doesn’t need to be complicated. With a straightforward function that traverses through child nodes, you can effectively identify the right elements while avoiding parent structures.

This method not only enhances your JavaScript skills but allows for greater control and flexibility in your web development projects. Feel free to adapt and expand upon this function to fit your specific needs!

Remember, the key to effective programming is finding solutions that balance efficiency and clarity.

Тэги:

#Find_element_containing_specific_text_with_vanilla_js #javascript
Ссылки и html тэги не поддерживаются


Комментарии: