How to Set new Attribute in XML using jQuery

By FoxLearn 2/8/2025 2:52:22 AM   25
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>