I tried to wrap some text in span depend on data-text
.
For example, if I have this code:
<div data-text="world">Hello World We Love JavaScript</div>
I'd like to wrap it like this:
<div data-text="world">Hello <span>World</span> We Love JavaScript</div>
I have tried to solve this problem using jQuery's replace()
method, but I have not yet found the right solution:
$("div").text(function (index, text) { return text.replace($("div").data("text"), "<span>" + $("div").data("text") + "</span>"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div data-text="Hello">Hello <span>World</span> We Love JavaScript</div>
Use html()
method with a callback and generate regex using the attribute value with word boundary (to match only the exact word) to replace the word with wrapped span.
$('div[data-text]').html(function(_, htm) { return htm.replace(new RegExp('\\\\b' + $(this).data('text') + '\\\\b', 'ig'), '<span>$&</span>') })
div span { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-text="Hello|love">Hello World We Love JavaScript</div>
You need to set html of element instead of text :
$("div").html(function(i,html) {
return html.replace(/(World)/g, '<span>World</span>');
});
$("div").html(function(i,html) { return html.replace(/(World)/g, '<span>World</span>'); });
<style>span{color:red}</style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div data-text="Hello">Hello <span>World</span> We Love JavaScript</div>
Try this code http://jsfiddle.net/wQns7/2138/
$("div").html(function () {
return $(this).html().replace("World", "<span>World</span>");
});
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.