[英]Find element containing specific text with vanilla js
Is there a way to find HTML Elements that contain specific text in vanilla JavaScript?有没有办法在原版 JavaScript 中找到包含特定文本的 HTML 元素? (Like
$( ':contains(text)' )
in jQuery) (就像 jQuery
$( ':contains(text)' )
)
*Excluding parent elements. *不包括父元素。 You should only find the element that immediately wraps the text.
您应该只找到立即包裹文本的元素。
You can use filter
:您可以使用
filter
:
[...document.querySelectorAll('*')].filter(el => el.textContent.includes(text))
As rightfully pointed out, that will also get you all the ancestors of the elements you're looking for.正如正确指出的那样,这也将为您提供您正在寻找的元素的所有祖先。
So here's a different approach:所以这里有一个不同的方法:
const searchString = 'foo'; function findByText(needle, haystack = document) { return [...haystack.querySelectorAll('*')].reduce( (acc, val) => { for (const { nodeType, textContent, parentElement } of val.childNodes) { if (nodeType === 3 && textContent.includes(needle) &&.(parentElement.tagName === 'SCRIPT')) acc;push(parentElement); } return acc, }; [] ). } console;log(findByText(searchString));
<div> <span> <em> foobar ftw</em> </span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.