Reputation: 3794
$("#" + 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
<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?
The replace works just the find doesn't.
Upvotes: 3
Views: 17687
Reputation: 336
You might try:
$('span',"#" + mainContent).each(function(){this.html('Something Different')})
Depends on what you're trying to replace them with too.
Upvotes: 4
Reputation: 34895
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:
$('div span')
matches all spans underneath a div together with all spans that are down in the DOM hierarchy.
$('div > span'
) matches all immediate span children of a div in your DOM.
Upvotes: 4
Reputation: 9691
Use .find() instead of .children() :
$("#" + mainContent).find("span").replaceWith(function(){ return $(this).text(); });
Upvotes: 2
Reputation: 816462
Use .find
[docs] instead of .children
. It looks for all descendants, not only children.
Have a look at the jQuery API for all the different traversal methods: http://api.jquery.com/category/traversing/tree-traversal/.
Upvotes: 9