Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
How to select element by ID in jQuery ?
Next article icon

How to replace HTML element in jQuery ?

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Replacing an HTML element in jQuery involves selecting an existing element on a webpage and replacing it with new content or another element. This process can be easily managed with jQuery methods like .replaceWith() or .html(), enabling dynamic and flexible content updates.

Syntax

replaceWith( newContent )
.replaceWith( function )

Return Value: This method returns the selected element with the change.

Note: The jQuery .replaceWith() method, returns the jQuery object so that the other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

Example 1: In this example we use jQuery to replace a paragraph with a styled <div> when the button is clicked. The replacement happens dynamically using the replaceWith() method, altering the content.

HTML
<!DOCTYPE html> <html>  <head>     <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">     </script>     <script>         $(document).ready(function () {             $("button").click(function () {                 $("p").replaceWith                     ("<div style='width:200px;height:100px;\                     background-color:red;text-align:center;\                     vertical-align:middle;display:table-cell'>\                     <strong>new div</strong></div>");             });         });     </script> </head>  <body>      <p>Example paragraph.</p>      <button style="margin: 20px 0px;">         click to replace     </button> </body>  </html> 

Output :

Example 2: In this example we use jQuery to replace a paragraph (<p>) with an <h1> tag when the button is clicked. The replacement is done dynamically using the replaceWith() method in jQuery.

XML
<!DOCTYPE html> <html>  <head>     <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">     </script>     <script>         $(document).ready(function () {             $("button").click(function () {                 $("p").replaceWith($("h1"))             });         });     </script> </head>  <body>      <p>Example paragraph.</p>      <button style="margin: 20px 0px;">         click to replace     </button>      <h1>H1 tag</h1> </body>  </html> 

Output :

Example 3: In this example we use jQuery to replace all elements with the class X (paragraph, heading, and div) with an <h3> element containing "new element" when the button is clicked.

HTML
<!DOCTYPE html> <html>  <head>     <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">     </script>     <script>         $(document).ready(function () {             $("button").click(function () {                 $(".X").replaceWith("<h3>new element</h3>")             });         });     </script> </head>  <body>      <p class="X">Example paragraph.</p>      <h1 class="X">Example H1</h1>     <div style="width: fit-content;                 background-color: green;                 padding: 10px;" class="X">         Example div     </div>     <button style="margin: 20px 0px;">         click to replace     </button> </body>  </html> 

Output :


Next Article
How to select element by ID in jQuery ?
author
varunkedia
Improve
Article Tags :
  • Web Technologies
  • JQuery
  • jQuery-Methods
  • jQuery-Questions

Similar Reads

  • How to select element by ID in jQuery ?
    In this article, we are going to see how to select the element by its id using jQuery. To learn about this topic one should have prior knowledge about HTML, CSS, JavaScript and jQuery. Using JavaScript: This question is also solved by a popular JavaScript method called document.getElementById() whic
    2 min read
  • How to use jQuery to Search and Replace HTML elements?
    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 ApproachIntegrate the jQuery library hosted on a content delivery net
    2 min read
  • How to change an HTML element name using jQuery ?
    Given an HTML document and the task is to replace an HTML element by another element. For example: we can change an element <b> with <h1> element without changing any other property.Approach: Select the HTML element which need to be change.Copy all attributes of previous element in an ob
    2 min read
  • How to Add Attributes to an HTML Element in jQuery?
    To add attributes to an HTML element in jQuery, the attr() method can be used. This allows to set one or more attributes for a selected element, such as id, class, src, and href. Approach: Given an HTML document containing <label>, <input>, and <button> elements. The <input>
    1 min read
  • How to select elements by attribute in jQuery ?
    jQuery is a lightweight JavaScript library. In the vanilla JavaScript language, the getElementById method is used to select an element. However, jQuery provides a much lighter alternative for the same purpose. The 'jQuery Selector' allows the user to manipulate HTML elements and the data inside it(D
    2 min read
  • jQuery element Selector
    jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax i
    1 min read
  • How to create an HTML element using jQuery ?
    In this article, we will see how to create an HTML element using jQuery. To create and append the HTML element, we use the jQuery append() method. The jQuery append() method is used to insert some content at the end of the selected elements. Syntax: $(selector).append( content, function(index, html)
    2 min read
  • How to replace innerHTML of a div using jQuery?
    For replacing innerHTML of a div with jquery, html() function is used. Syntax: $(selector).html() Example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> changing-innerhtml-using-jquery </title> <link href= "http
    1 min read
  • How to get the outer html of an element using jQuery ?
    Sometimes, there is a need to get the entire HTML element by its id and not merely its contents, for doing so, we shall use the HTML DOM outerHTML Property to get the outer HTML of HTML element. Syntax: document.getElementById("your-element-id").outerHTML) You can use a variable and initialize it to
    2 min read
  • How to Use jQuery $(this) in Event ?
    The scope of this keyword changes according to the scope of the object. The $(this) keyword will refer to the selected element to which the event is attached when used in an event. In this article, we will see the implementation of $(this) with an event in different conditions. Syntax:$('element_sel
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences