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?
For your current example here is my one line solution:
$("div span").detach().prependTo($("div").contents().wrap("<span />").end());
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
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.