What you could use is the .html()
method. You can access the HTML of the element in a function as the second argument. However, using body
as a selector is dangerously broad—narrowing down your range of selectors will also help greatly with performance.
Mistake: using .html()
is extremely risky because you might end up replacing numerical attributes in HTML elements/tags. A better solution would be to fetch the text nodes in all children of the <body>
element (although changing the selector to be more specific will help), using a previously published method, will work.
The code consist of two loops:
- The first loop iterates through all descendents of the
<body>
element, i.e. using $('body').find('*').each(function() {...});
—this is very costly. You should narrow down your selectors to achieve better performance.
- The second loop occurs after retrieving the content of each child, using
.contents()
, and then filtering based on node type using .filter()
. This gives us all text nodes in the body element. We simply replace these text nodes with the regex you have defined.
p/s: It's a good idea to separate the styling from your JS code, unless it has to be specific depending on context. Otherwise, simply declare an appropriate class and style it any way you desire:
$('body').find('*').each(function() {
$(this).contents().filter(function () {
return this.nodeType === 3;
}).each(function () {
$(this).replaceWith($(this).text().replace(/(\d+)/g, '<span class="number">$1</span>'));
});
});
span.number {
font-size: 30px;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Over $2000.</p>
<div><p>Over $3000.</p></div>