PGB
PGB

Reputation: 23

Get Child Nodes attribute value using DOM parser in Javascript

I need to get the value of "templatedata" (RK1S) using JavaScript.

<additional_info>
<Param name="srno" value="B4745" />
<Param name="Device" value="Opn" />
<Param name="Support" value="0" />
<Param name="templatedata" value="Rk1S"/>
</additional_info>

I tried with the following script but I'm getting undefined.

var text=" <additional_info>
    <Param name="srno" value="B4745" />
    <Param name="Device" value="Opn" />
    <Param name="Support" value="0" />
    <Param name="templatedata" value="Rk1S"/>
    </additional_info>";

if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(text,"text/xml");
} else {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(text); 
} 


var txt;
var x = xmlDoc.getElementsByTagName("additional_info");
alert(x[0].value);
var y=x.getAttribute("Param name")
txt = y.nodeValue;
alert(txt);

Upvotes: 0

Views: 1406

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370739

All you need is querySelector for the element you want, which can be selected with Param[name="templatedata"]. Use a template literal instead of double quotes to define a string over multiple lines, and use getAttribute('value') instead of .value, because .value only works for input-like elements:

var text = `<additional_info>
<Param name="srno" value="B4745" />
<Param name="Device" value="Opn" />
<Param name="Support" value="0" />
<Param name="templatedata" value="Rk1S"/>
</additional_info>`;

let parser;
let xmlDoc;
if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(text, "text/xml");
} else {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(text);
}
const param = xmlDoc.querySelector('Param[name="templatedata"]');
console.log(param.getAttribute('value'));

Upvotes: 2

Related Questions