为什么xhr.responseXML.getElementsByClassName('clazz')不起作用?
这是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包含以下内容:
<?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>
你可以在Chrome控制台中解释以下输出吗?
xhr.responseXML.getElementById('x')
<div id="x" class="y"></div>
xhr.responseXML.getElementsByClassName('y')
[]
3 回答
xhr.responseXML是XML节点而不是HTML元素,这意味着class属性没有特殊含义 .
但是,当我将xmlns声明添加到html标记时,responseXML上的getElementsByClassName才起作用(在Chrome上测试) .
因为它在您的节点上找到
innerHTML
属性 .虽然getElementsByClassName()不起作用,但getElementsByTagName()会;和标签有属性 .
现在数组变量XMLclassY将作为getElementsByClass();应该 .