
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change HTML Element Name Using jQuery
jQuery is a JavaScript library created to make event handling, CSS animation, Ajax, and DOM tree navigation and manipulation easier. In this article we are going to see how we can change the name of an element using jQuery.
Algorithm
We are going to follow a three?way procedure to change the name of any element using jQuery:
Identify and select the element we want to change.
Copy all the attributes of the selected element to a temporary object.
Create a new element with the new name and copy all the attributes to it. Replace the old element with this new element.
Example
Let us go through an example to get a better understanding.
Step 1: First we will define the HTML file.
<!DOCTYPE html> <html> <head> <title>How to change an HTML element name using jQuery?</title> </head> <body> <h4>How to change an HTML element name using jQuery?</h4> <div> <button id="main">CLICK!</button> </div> </body> </html>
Step 2: Now we will use CSS to provide some styling to the page.
<style> #main { border-radius: 10px; } </style>
Step 3: We will now import jQuery to the webpage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Step 4: We will now add the logic to perform the name change once the button is clicked.
<script> let btn = document.getElementById("main"); btn.onclick = () => { let attribute = {}; $.each($("h4")[0].attributes, function (id, atr) { attribute[atr.nodeName] = atr.nodeValue; }); $("h4").replaceWith(function () { return $("<h1 />", attribute).append($(this).contents()); }); } </script> </body>
Here is the complete code:
<!DOCTYPE html> <html> <head> <title>How to change an HTML element name using jQuery?</title> <style> #main { border-radius: 10px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <h4>How to change an HTML element name using jQuery?</h4> <div> <button id="main">CLICK!</button> </div> <script> let btn = document.getElementById("main"); btn.onclick = () => { let attribute = {}; $.each($("h4")[0].attributes, function (id, atr) { attribute[atr.nodeName] = atr.nodeValue; }); $("h4").replaceWith(function () { return $("<h1 />", attribute).append($(this).contents()); }); } </script> </body> </html>
Conclusion
In this article, we learn how we can use jQuery to change the name of any element. To do so we applied a simple approach where we identified the element, preserved its attributes and then replaced it with a new element with the same attributes.