Reputation: 17467
I have the following
<div><span class="myspan">hello</span> this text has no span </div>
In jQuery, how can I wrap a div
or span around the "this text has no span" text?
Upvotes: 6
Views: 3206
Reputation: 7743
You can search for any text (nodeType:3) element in the parent div and then wrap each text in another div. See below example:
$('#myDiv').contents().filter(function(){
return this.nodeType === 3;
}).wrapAll("<div class='red' />");
.red { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><span class="myspan">Hello</span> this text has no span </div>
Upvotes: 0
Reputation: 15433
It would not be the best solution but can help you...
<div id="myDiv"><span class="myspan">hello</span> this text has no span </div>
var div = $('div#myDiv');
var span = $('span.myspan');
div.remove(span);
div.html($('<span></span>').text(div.text()));
I guess you have the idea what i am trying to do
Upvotes: 0
Reputation: 145368
For your current example here is my one line solution:
$("div span").detach().prependTo($("div").contents().wrap("<span />").end());
DEMO: http://jsfiddle.net/awwTA/
Upvotes: 8