Toniq
Toniq

Reputation: 5016

Parse with DOMParser or innerHTML?

What is the difference between these examples and why would you use one instead of another, for performance or browser compatibility? Is there something cannot be done between these two?

txt="<address>"+
 "<street>Roble Ave</street>"+
  "<mtfcc>S1400</mtfcc>"+
  "<streetNumber>649</streetNumber>"+
  "<lat>37.45127</lat>"+
  "<lng>-122.18032</lng>"+
  "<distance>0.04</distance>"+
  "<postalcode>94025</postalcode>"+
  "<placename>Menlo Park</placename>"+
  "<adminCode2>081</adminCode2>"+
  "<adminName2>San Mateo</adminName2>"+
  "<adminCode1>CA</adminCode1>"+
  "<adminName1>California</adminName1>"+
  "<countryCode>US</countryCode>"+
 "</address>";
 
 var d = document.createElement('div')
 d.innerHTML = txt

console.log(d.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
console.log(d.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);

or

txt = "<address>" +
  "<street>Roble Ave</street>" +
  "<mtfcc>S1400</mtfcc>" +
  "<streetNumber>649</streetNumber>" +
  "<lat>37.45127</lat>" +
  "<lng>-122.18032</lng>" +
  "<distance>0.04</distance>" +
  "<postalcode>94025</postalcode>" +
  "<placename>Menlo Park</placename>" +
  "<adminCode2>081</adminCode2>" +
  "<adminName2>San Mateo</adminName2>" +
  "<adminCode1>CA</adminCode1>" +
  "<adminName1>California</adminName1>" +
  "<countryCode>US</countryCode>" +
  "</address>";

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


console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);

http://jsfiddle.net/ub4mL80s/

http://jsfiddle.net/nm9yd0xz/1/

Upvotes: 1

Views: 972

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

One potential problem is that assigning to the innerHTML of a newly created element can execute inline handlers inside the txt:

const txt = `
 <address>
 <street>Roble Ave</street>
 ...
 </address>
 <img src="nosrc" onerror="alert('evil');">
 `;

const d = document.createElement('div')
d.innerHTML = txt

// navigate through d

If the txt can contain arbitrary data, this is a security risk. DOMParser is much safer, because it doesn't have this vulnerability.

Also note that you can greatly simplify your

d.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue

to

d.querySelector('streetNumber').textContent

Also note that jQuery is not involved in any of this - this is only Javascript.

Upvotes: 3

Related Questions