How to Set new Attribute in XML using jQuery
By Tan Lee Published on Feb 08, 2025 135
To set a new attribute in XML using jQuery, you follow a similar approach to manipulating HTML elements, but with XML data.
If you need to add a new attribute to an XML element using jQuery, you can follow the example below.
<data> <item id="1">Apple</item> </data>
You can add an attribute to any XML tag in the same way you would for HTML elements. First, save your XML in a variable, like this:
var xmlData = '<data><item>Apple</item></data>'; xmlData = $(xmlData); xmlData.find('item').attr('category', 'fruit');
This will add the category
attribute to the <item>
tag with the value fruit
.
Another Example Using a Function to Set an Attribute
You can also create a function to add an attribute to any specific XML node. Here's an example that demonstrates how to add an attribute using a method called SetAttribute
.
var SetAttribute = function (attributeName, attributeValue, xmlString, nodeName) { // parameter : attributeName, the name of the attribute. // parameter : attributeValue, the value for the new attribute. // parameter : xmlString, the complete XML string where the node exists. // parameter : nodeName, the name of the node to which the attribute will be added. var updatedXML = ""; var xmlDoc = $.parseXML(xmlString); var $xml = $(xmlDoc); if (!nodeName) { // If no node is specified, add the attribute to the root element updatedXML = $xml.attr(attributeName, attributeValue); } else { // Otherwise, add the attribute to the specific node updatedXML = $xml.find(nodeName).attr(attributeName, attributeValue); } xmlString = updatedXML[0].outerHTML; return xmlString; };
Example Usage:
To add a category
attribute with the value fruit
to the <item>
tag in the XML, use the function like this:
var xmlString = '<data><item>Apple</item></data>'; var updatedXML = SetAttribute("category", "fruit", xmlString, "item"); console.log(updatedXML);
Output:
<data> <item category="fruit">Apple</item> </data>
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Motiv MUI React Admin Dashboard Template
Nov 19, 2024
K-WD Tailwind CSS Admin Dashboard Template
Nov 17, 2024