How to use jQuery to Search and Replace HTML elements?
Last Updated :
18 Jun, 2024
Improve
Using jQuery, you can dynamically search and replace HTML elements on a webpage. By selecting elements and binding actions to events, you can manipulate their content or structure in response to user interactions or other triggers
Approach
- Integrate the jQuery library hosted on a content delivery network (CDN), ensuring access to jQuery functionalities.
- Two buttons with classes "one" and "two" are defined, each bound to a click event handler using jQuery.
- When the "Correct Me!" button is clicked, jQuery targets the
<h1>
element and replaces its text content with "Geeks for Geeks!". - Upon clicking the "Add Me!" button, jQuery targets a
<span>
element and replaces its HTML content with an<h3>
element containing the text "You can also Contribute.". - Basic CSS styles are applied to
<h1>
elements to change their color to green and align the body content to the center.
Example: The below example shows the above-explained approach.
<!DOCTYPE html>
<html>
<head>
<title>jQuery!!!</title>
<script type="text/javascript"
src="https://code.jquery.com/jquery-3.5.1.min.js">
</script>
<style type="text/css">
h1 {
color: green;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>Geeks Geeks</h1>
<br>
<button class="one">Correct Me!</button>
<br>
<br>
<button class="two">Add Me!</button>
<br>
<span></span>
<script type="text/javascript">
$(".one").click(function () {
$("h1").text("Geeks for Geeks!");
});
$(".two").click(function () {
$("span").html("<h3>You can also Contribute.</h3>");
});
</script>
</body>
</html>
Output:
