If you want to add new attribute in XML using jQuery. Let’s check how to do this using below sample xml.

<data>
<section marked="marked"></section>
</data>

You can add attribute in any XML tag as you add in case of HTML. First your XML is saved in any variable like given below.

var a = '<data><section></section></data>';
a = $(a);
a.find('section').attr('marked', 'marked');   

/// Above line will add an attribute in section tag.

One more example:

You will call “SetAttribute” method (given below) to add attribute in given XML. Please check below the syntax as shown below:

SetAttribute("marked", "marked",FullXmlAsString,"section" ) 
var SetAttribute = function (id, value, sourceXML, specificNode) {
        //param :id,  id of XML node.
        //param : value, value of the new node.
        //param :sourceXML, it is the complete XML text  in which node need to be added.
        //param :specificNode, it is the name of node which will get addded in above complete XML and  then final text will get returned. 
        var test = "";
        var xmlDoc = $.parseXML(sourceXML);
        $xml = $(xmlDoc);
        if (specificNode === undefined || specificNode === "") {
            test = $xml.attr(id, value); //will add prpty at root
        } else {
            //var test = $xml.find('section').attr('marked', 'marked');
            test = $xml.find(specificNode).attr(id, value);
        }
        sourceXML = test[0].outerHTML;
       
        return sourceXML;
    };

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore More

How to Center a Popup Window on Screen

JavaScript window.open() method is used to open a popup window. This popup window will be placed in the center of the screen. This example creates the pop-up window without placing it into

How to hide URL in the popup window opened using window.open

If you are using below code to open a popup window in your web page, then address must be appearing in you pop up window and f you want to

window.showModalDialog is deprecated in Edge and Chrome

If you have a website being compatible with Edge/Chrome and in past it was only compatible with IE 11 and if you are using window.showModalDailog in your JavaScript code, then