Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap part of the text with spans using jQuery?

Here is what I am trying to do

Fox<span>Rox</span>

before that

FoxRox

How do I wrap spans around Rox?

like image 302
phoxd Avatar asked May 04 '12 04:05

phoxd


People also ask

What is wrap method in jQuery?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector). wrap(wrappingElement,function(index))

How do you wrap an element in a div?

Wrap a set of elements Select the element or elements that you want to enclose in a div. Use one of the following methods to wrap the selected elements: Select Edit > Wrap from the top menu.

Does span have textContent?

Use the textContent property to get the text of a span element, e.g. const text = span. textContent . The textContent property will return the text content of the span and its descendants. If the element is empty, an empty string is returned.


1 Answers

This will search you whole DOM and replace each Rox with <span>Rox</span>:

$(':contains("Rox")').html(function(index, oldHTML) {
    return oldHTML.replace(/(Rox)/g, '<span>$&</span>');
});​

Live DEMO

like image 156
gdoron is supporting Monica Avatar answered Oct 20 '22 03:10

gdoron is supporting Monica