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

article image
»

jQuery’s .children() Method

Just like in CSS, it’s possible to use jQuery to select the ...

article image
»

jQuery’s .click() Method

With jQuery, it’s super easy to make something happen as a result ...

article image
»

Using jQuery’s .resize() Method

jQuery’s .resize() method is a cool way to have an event ...

article image
»

How to Use jQuery to Search and Replace HTML

Have you ever made a mistake in your code or in your text and dreaded ...

article image
»

How to Use jQuery’s .mouseover() Method

jQuery’s .mouseover() method is used to execute some jQuery ...

article image
»

How to Use jQuery’s .blur() Method

jQuery’s .blur() method isn’t exactly what it sounds like ...

article image
»

jQuery 3.0: Fix url.indexOf is Not a Function Error

jQuery 3.0 is out, and if you started working with it and plan to ...

article image
»

Set/Get/Delete Cookies with jQuery

There are a lot of plugins you can use to set, get, and delete ...

Screen Shot 2016-11-26 at 12.05.09 PM
»

3 Best jQuery Video Gallery Plugins

Do you have a lot of videos that you’d like to embed or neatly ...