X

LATEST #JQUERY NEWS

How to Use jQuery to Search and Replace HTML


Have you ever made a mistake in your code or in your text and dreaded combing through all of your HTML files to repair what went awry? With this jQuery search and replace code, you may never have to do that again. The code searches for a term or word in your HTML files and then replaces that term or word with whatever you like, much like the search and replace functionalities on your favorite word processor or text editor.

If you want to see how the code works, take a look at the snippet below:

$(function () {
 $(":contains(FIND)").not(":has(:contains(FIND))").each(function () {
 var that = $(this),
 html = that.html();
 html = html.replace(/(\(FIND:.*?\))/g, "REPLACE-WITH");
 that.html(html);
 });
});

If you want to use the example above to perform your own search and replace functionality, you’ll need to replace the word “FIND” with the phrase you’re searching for, and the term “REPLACE-WITH” with, naturally, whatever you’d like to replace the “FIND” element with.

Make sure you exercise caution when using this snippet, because you could potentially cause some serious errors if you accidentally search and replace some valuable/necessary code or HTML elements. This code will replace every single instance of the “FIND” item, so always bear that in mind.

Recently Published

Screen Shot 2017-04-23 at 10.15.41 AM
»

How to Use jQuery to Create a Sticky Navigation on Scroll

Creating “sticky” elements is something that can often be ...

article image
»

How to Use jQuery’s Keystroke Methods

jQuery has a few built-in keystroke methods that are all triggered by ...

article image
»

How to Change iFrame Styling Using jQuery

If you’ve ever had the displeasure of working with iFrames, ...

article image
»

How to Use jQuery to Create Blinking Text

Blinking text is one of those cool features that you never actively ...

article image
»

Convert Images to Black and White using jQuery

Converting an image to black and white is no longer a manual event. ...

article image
»

How to Disable Right-Click Menu Using jQuery

There can be dozens of reasons why you may want to disable right ...

article image
»

How to Optimize jQuery Code for Better Performance

jQuery is the most popular client side library, in fact almost every ...

article image
»

Using Head.js to Load All Your JavaScript

In the past few years, client side frameworks/libraries have become ...

article image
»

How to Detect Browser Using jQuery

One of the more frustrating parts of creating a new web project is ...