$("#" + mainContent).children("span").replaceWith(function(){ return $(this).text(); });
使用上面的代码行我似乎无法用文本值替换所有跨度。
html看起来像
<div id="bla" contenteditable="true">
<span> bla finds this one</span>
<div>
<span> doesnt find me </span>
</div>
</div>
如何选择div“bla”中的所有跨度并全部替换它们?
替换工作只是找不到。
使用.find
[docs]而不是.children
。它寻找所有后代,而不仅仅是孩子。
查看所有不同遍历方法的jQuery API:http://api.jquery.com/category/traversing/tree-traversal/。
jQuery的children()
函数只匹配直接的孩子。在你的DOM结构的情况下,只有一个<span>
元素是你的选择器匹配的<div>
的直接子元素。如果要查找由选择器匹配的元素层次结构下的所有元素,则需要使用find()
在层次结构中执行搜索,或者您必须修改选择器:
$('div span')
匹配div下面的所有跨距以及DOM层次结构中的所有跨距。
$('div > span'
)匹配DOM中div的所有直接跨度子节点。
你可以试试:
$('span',"#" + mainContent).each(function(){this.html('Something Different')})
取决于你想要替换它们的东西。
使用.find()代替.children():
$("#" + mainContent).find("span").replaceWith(function(){ return $(this).text(); });