javascript jQuery 选择器,DIV 中的所有跨度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12247184/
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, All Spans Within DIV
提问by LmC
$("#" + mainContent).children("span").replaceWith(function(){ return $(this).text(); });
Using the above line of code I can't seem to replace all spans with there text value.
使用上面的代码行,我似乎无法用文本值替换所有跨度。
The html looks like
html看起来像
<div id="bla" contenteditable="true">
<span> bla finds this one</span>
<div>
<span> doesnt find me </span>
</div>
</div>
How do I select all spans within div "bla" and replace them all?
如何选择div“bla”中的所有跨度并将它们全部替换?
The replace works just the find doesn't.
替换工作只是发现没有。
回答by Felix Kling
Use .find
[docs]instead of .children
. It looks for all descendants, not only children.
使用.find
[docs]而不是.children
. 它寻找所有后代,而不仅仅是孩子。
Have a look at the jQuery API for all the different traversal methods: http://api.jquery.com/category/traversing/tree-traversal/.
查看所有不同遍历方法的 jQuery API:http: //api.jquery.com/category/traversing/tree-traversal/。
回答by Sam Mirrado
You might try:
你可以试试:
$('span',"#" + mainContent).each(function(){this.html('Something Different')})
Depends on what you're trying to replace them with too.
也取决于你想用什么来替换它们。
回答by Konstantin Dinev
The children()
function of jQuery matches only immediate children. In the case of your DOM structure there is only one <span>
element that is an immediate child of the <div>
that your selector matches. In the case where you want to find all elements that are underneath the hierarchy of the element matched by your selector you would need to either use find()
which performs a search down the hierarchy or you would have to modify your selector:
children()
jQuery的功能只匹配直接子元素。在您的 DOM 结构的情况下,只有一个<span>
元素是<div>
您的选择器匹配的直接子元素。如果您要查找选择器匹配的元素层次结构下的所有元素,则需要使用find()
which 在层次结构中执行搜索,或者您必须修改选择器:
$('div span')
matches all spans underneath a div together with all spans that are down in the DOM hierarchy.
$('div span')
匹配 div 下的所有跨度以及 DOM 层次结构中的所有跨度。
$('div > span'
) matches all immediate span children of a div in your DOM.
$('div > span'
) 匹配 DOM 中 div 的所有直接跨度子级。
回答by gabitzish
Use .find() instead of .children() :
使用 .find() 而不是 .children() :
$("#" + mainContent).find("span").replaceWith(function(){ return $(this).text(); });