为什么getElementsByClassName在xhr reponseXML上不起作用

为什么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')
[]

xhr.responseXML是XML节点,而不是HTML元素,这意味着class属性没有特殊含义。

但是,当我向html标签添加xmlns声明时,responseXML上的getElementsByClassName正常工作(在Chrome上测试)。

<html xmlns="http://www.w3.org/1999/xhtml">

因为它是XML,而不是HTML。 您也不会在节点上找到innerHTML属性。


虽然getElementsByClassName()不会工作,getElementsByTagName()会; 并且标签具有属性。

var XMLtagDIV = xhr.getElementsByTagName('div');
var XMLclassY = []; 
var counter = 0;         //Keep class array incrementally uniform e.g. 0,1,2,3,4...
 for(i=0; i<XMLtagDIV.length; i++) 
{ 
  if(XMLtagDIV[i].getAttribute('class') == 'y') { 
   counter++;                            
   XMLclassY[counter] = XMLclassY;  }    
}

现在数组变量XMLclassY的行为就像getElementsByClass(); 应该。

链接地址: http://www.djcxy.com/p/48223.html

上一篇: Why getElementsByClassName doesn't work on xhr reponseXML

下一篇: touch associate model in the same way JSON is nested