Home Articles

为什么getElementsByClassName不适用于xhr reponseXML

Asked
Viewed 1261 times
0

为什么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 Answers

  • 1

    虽然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();应该 .

  • 0

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

    但是,当我将xmlns声明添加到html标记时,responseXML上的getElementsByClassName才起作用(在Chrome上测试) .

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

    因为它在您的节点上找到 innerHTML 属性 .

Related