Why xhr.responseXML.getElementsByClassName('clazz') doesn't work?
Here is the js:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var happiness = xhr.responseXML.getElementsByClassName('clazz');
//Uncaught TypeError: Cannot read property 'innerHTML' of undefined
console.log("happiness ? " + happiness[0].innerHTML);
}
};
//xhr.overrideMimeType("application/xml");
xhr.open("GET", "xhr.php", true);
xhr.send(null);
xhr.php contains the following:
<?php
header('Content-type: application/xml; charset=UTF-8');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
?>
<!DOCTYPE html>
<html>
<head>
<title>I'm the XHR response</title>
</head>
<body>
<div class="clazz">xhr happiness</div>
<div id="x" class="y"></div>
</body>
</html>
can you please explain the following output in the Chrome console?
xhr.responseXML.getElementById('x')
<div id="x" class="y"></div>
xhr.responseXML.getElementsByClassName('y')
[]
getElementsByClassNameis not a base DOM method, it's a method of the DOM HTML extension. There is no concept of classes in XML. - Felix Kling