How to wrap around part of text inside an element?

只谈情不闲聊 提交于 2019-12-11 18:29:00

问题


Let's say I have the sentence:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

inside a <p> tag. I would like to somehow use javascript to create an element around the word amet, e.g.:

Lorem ipsum dolor sit <span>amet</span>, consectetur adipiscing elit.

Is there some sort of way to do this? In the real-world application for this, I won't know what text I want to have an element around, so I can't just modify the HTML.


回答1:


One option is using replace method.

$('p').html(function(index, oldHtml){
   return oldHtml.replace(/(amet)/g, '<span>$1</span>');
});

http://jsfiddle.net/YxMvq/



来源:https://stackoverflow.com/questions/14676642/how-to-wrap-around-part-of-text-inside-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!