redochka
redochka

Reputation: 12839

Why getElementsByClassName doesn't work on xhr reponseXML

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

Upvotes: 2

Views: 1754

Answers (3)

redochka
redochka

Reputation: 12839

xhr.responseXML is XML nodes and not HTML elements which means that class attribute has not a special meaning.

However, when I added xmlns declaration to the html tag, the getElementsByClassName on responseXML just worked (tested on Chrome).

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

Upvotes: 1

Simeon
Simeon

Reputation: 836

While getElementsByClassName() wont work, getElementsByTagName() will; and tags have Attributes.

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;  }    
}

Now the array variable XMLclassY will act just as getElementsByClass(); should.

Upvotes: 3

Bergi
Bergi

Reputation: 665286

Because it's XML, not HTML. You also won't find innerHTML properties on your nodes.

Upvotes: 1

Related Questions