javascript 用于直接包含文本的元素的 jQuery 选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7896455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery selector for an element that directly contains text?
提问by Abe Miessler
I was able to get this partially working using the :contains
selector, but my problem is if an element contains an element that contains the text it is still returned. For example:
我能够使用:contains
选择器使其部分工作,但我的问题是如果一个元素包含一个包含它仍然返回的文本的元素。例如:
$('div:contains("test")')
Will select both divs below:
将选择以下两个 div:
<div>something else
<div>test</div>
</div>
fiddle: http://jsfiddle.net/TT7dR/
小提琴:http: //jsfiddle.net/TT7dR/
How can I select only divs that "directly" contain the text? Meaning that in the above example only the child div would be selected.
如何仅选择“直接”包含文本的 div?这意味着在上面的例子中只会选择子 div。
UPDATE:
更新:
Just to clarify, if I were searching for the text "something else" instead of "test" then I would like to only find the parent div.
只是为了澄清,如果我要搜索文本“别的东西”而不是“测试”,那么我只想找到父 div。
采纳答案by bobince
$('div>:contains("test")')
is not a general solution, it only works for your specific example. It still matches any element whose descendants contain the text test
, as long as its parent is a div
.
$('div>:contains("test")')
不是通用解决方案,它仅适用于您的特定示例。它仍然匹配其后代包含文本的任何元素test
,只要其父元素是div
。
There is in fact currently no selector that will select only direct parents of text nodes containing your target text. To do it you would have to walk the DOM tree yourself checking each text node you find for the target text, or write a plugin to do the same. It'd be slow, but then not as slow as :contains
already is (it's not a standard CSS selector so you don't get browser-native fast selector support).
事实上,目前没有选择器只选择包含目标文本的文本节点的直接父节点。为此,您必须自己遍历 DOM 树,检查为目标文本找到的每个文本节点,或者编写一个插件来执行相同操作。它会很慢,但不会像现在那样慢:contains
(它不是标准的 CSS 选择器,因此您无法获得浏览器原生的快速选择器支持)。
Here's a plain DOM function you could use as a starting point. It might be improved to find text in adjacent (non-normalised) text nodes, or to hide it in a plugin/selector-extension.
这是一个简单的 DOM 函数,您可以将其用作起点。在相邻(非规范化)文本节点中查找文本或将其隐藏在插件/选择器扩展中可能会得到改进。
function findElementsDirectlyContainingText(ancestor, text) {
var elements= [];
walk(ancestor);
return elements;
function walk(element) {
var n= element.childNodes.length;
for (var i= 0; i<n; i++) {
var child= element.childNodes[i];
if (child.nodeType===3 && child.data.indexOf(text)!==-1) {
elements.push(element);
break;
}
}
for (var i= 0; i<n; i++) {
var child= element.childNodes[i];
if (child.nodeType===1)
walk(child);
}
}
}
回答by Kai Noack
Just to complete the knowledge base. If you need to get all DOM elements within the body (not only DIVs) that contain specific text or characters you can use:
只是为了完成知识库。如果您需要获取包含特定文本或字符的正文中的所有 DOM 元素(不仅是 DIV),您可以使用:
function getNodesThatContain(text) {
var textNodes = $(document).find(":not(iframe, script)")
.contents().filter(
function() {
return this.nodeType == 3
&& this.textContent.indexOf(text) > -1;
});
return textNodes.parent();
};
console.log(getNodesThatContain("test"));
Hope that helps.
希望有帮助。
jsfiddle: http://jsfiddle.net/85qEh/2/
jsfiddle:http: //jsfiddle.net/85qEh/2/
Credits: DMoses
学分:DMoses
回答by rkw
You might have to do an in-efficient query. Do not use this solution if someone finds a selector that manages to filter out child elements: http://viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html
您可能必须执行效率低下的查询。如果有人找到一个可以过滤掉子元素的选择器,请不要使用此解决方案:http: //viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html
$("div:contains('test')")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.filter(":contains('test')")
edit: that snippet above is just to test the element, in implementation it would look more like this: http://jsfiddle.net/rkw79/TT7dR/6/
编辑:上面的片段只是为了测试元素,在实现中它看起来更像这样:http: //jsfiddle.net/rkw79/TT7dR/6/
$("div:contains('test')").filter(function() {
return (
$(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.filter(":contains('test')").length > 0)
}).css('border', 'solid 1px black');
回答by Hussam
try adding the greater than:
尝试添加大于:
$('div>:contains("test")')
回答by Clive
This seems to work for me:
这似乎对我有用:
$('div >:contains("test")');
This forces the matched :contains
selector to be a direct child of the <div>
element
这会强制匹配的:contains
选择器成为<div>
元素的直接子元素
回答by Yuvaraj Gunisetti
Try the following:
请尝试以下操作:
$("div>div:contains(test):only-of-type")
回答by Jor
Finds specific element, but not parents
查找特定元素,但不查找父元素
var elementsContainingText = ($(':contains("' + text + '")', target)).filter(function() {
return $(this).contents().filter(function() {return this.nodeType === 3 && this.nodeValue.indexOf(text) !== -1; }).length > 0;
});
回答by Ari
回答by user1405377
You can simply select the element that doesn't have your element
您可以简单地选择没有您的元素的元素
$('div:contains("test"):not(:has(> div))')
回答by Matthias Gwiozda
less code to write (but with a little limitation):
编写更少的代码(但有一点限制):
let selector = $('div:contains("test")');
selector.not(selector.has('div:contains("test")'))
Just use the jQuery function (.has
) because the css :has
is experimental:
https://developer.mozilla.org/en-US/docs/Web/CSS/:has#Browser_compatibility
只需使用 jQuery 函数 ( .has
) 因为 css:has
是实验性的:https: //developer.mozilla.org/en-US/docs/Web/CSS/:
has#Browser_compatibility
Limitation:
局限性:
When you have a structure like this:
当你有这样的结构时:
<div>
<div>test</div>
test
</div>
Then only the inner div - Element will be found by this solution. This is because there is still an Element - Child of the div that :contains the string "test".
那么这个解决方案只会找到内部的 div - Element 。这是因为仍然有一个元素 - div 的子元素:包含字符串“test”。