By Leo Selig

2011-09-30 19:30:06 8 Comments

(I ask my question again after the first one was terribly formulated)

I face the following problem:

<div class="testA" id="test1"></div>

The above written element is predefined. I now load a xml tree via XMLHttpRequest & Co. delivering the following response:

    <div class="colorSelector" id="0-0">
        <div class="gbSelector" id="1-0">
            <table style="none" id="2-0"></table>

I now append the first div using


into the predefined div

<div class="testA" id="test1">

The final document looks like this (checked using development tools):

<div class="testA" id="test1">
    <div class="colorSelector" id="0-0">
        <div class="gbSelector" id="1-0">
            <table style="none" id="2-0"></table>

When I now try to get the element <div class="colorSelector" id="0-0"> using getElementById("0-0") I get the expected result.

But using getElementsByClassName("colorSelector") returns [].

Did I miss something? Is it probably a leftover of the fact the nodes were of type Element and not HTMLElement?


@Shadow2531 2011-09-30 20:10:43

Here's a way to do it for Firefox, Opera, Chrome and Safari. Basically, you just do div.innerHTML = div.innerHTML to reinterpret its content as HTML, which will make that class attribute from the XML file be treated as an HTML class name.

<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8">
            window.addEventListener("DOMContentLoaded", function() {
                var div = document.getElementsByTagName("div")[0];
                var req = new XMLHttpRequest();
                req.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                        var doc = this.responseXML;
                        div.appendChild(document.importNode(doc.getElementsByTagName("response")[0].getElementsByTagName("div")[0], true));
                        div.innerHTML = div.innerHTML;
      "GET", "div.xml");
            }, false);
        <div class="testA"></div>

Remove the this.status === 200 if you're testing locally in browsers that support xhr locally.

The importNode() function doesn't seem to work in IE (9 for example). I get a vague "interface not supported" error.

You could also do it this way:

var doc = this.responseXML;
var markup = (new XMLSerializer()).serializeToString(doc.getElementsByTagName("response")[0].getElementsByTagName("div")[0]);
div.innerHTML = markup;

as long as the markup is HTML-friendly as far as end tags for empty elements are concerned.

@Leo Selig 2011-10-01 08:55:55

i tried this but confusingly I still just get [] returned when using document.getElementsByClassName("colorSelector") whereas it works fine using document.getElementById("0-0")

@Shadow2531 2011-10-01 14:36:30

@Leo Selig, I accidentally had this.responseXML.document instead of just this.responseXML. It works in FF, Opera, Chrome and Safari for me. Doesn't seem to work in IE9 though. Something with the importNode maybe.

@Shadow2531 2011-10-01 14:56:11

@Leo Selig, I added another way to do it.

@bobince 2011-09-30 19:59:30

I now append the first div

How do you do that? What you have in the responseXML are XML elements, and not HTML elements.

  • You shouldn't be able to appendChild them into a non-XHTML HTML document;

  • actually you shouldn't be able to appendChild them into another document at all, you're supposed to use importNode to get elements from one document to another, otherwise you should get WRONG_DOCUMENT_ERR;

  • even if you managed to insert them into an HTML due to browser laxness, they're still XML elements and are not semantically HTML elements. Consequently there is nothing special about the class attributes; just having that name doesn't make the attribute actually represent a class. getElementsByClassName won't return elements just because they have attributes with the name class; they have to be elements whose language definition associates the attributes with the concept of classness (which in general means HTML, XHTML or SVG).

(The same should be true of the id attributes; just having an attribute called id doesn't make it conceptually an ID. So getElementById shouldn't be working. There is a way to associate arbitrary XML attributes with ID-ness, which you don't get with class-ness, by using an <!ATTLIST declaration in the doctype. Not usually worth bothering with though. Also xml:id is a special case, in implementations that support XML ID.)

You could potentially make it work if you were using a native-XHTML page by putting suitable xmlns attributes on the content to make it actual-XHTML and not just arbitrary-XML, and then using importNode. But in general this isn't worth it; it tends to be simpler to return HTML markup strings (typically in JSON), or raw XML data from which the client-side script can construct the HTML elements itself.

@Leo Selig 2011-09-30 20:18:31

thank you very much, I thought it would be a consequence of mixing up xml with html nodes but I didn't know exactly why

@Leo Selig 2011-10-01 08:58:50

another question to that: how do you thinkt i should construct the html elements from a string (i prefer solutions without innerHTML) or xml data (do you think of a complete "recreation" of the xml nodes as html elements?)

@bobince 2011-10-01 09:09:06

importNode should be able to recreate XML nodes as HTML nodes but there are browser difficulties (especially IE where you don't even get the method). I don't think I'd try to put HTML elements inside XML as elements; the languages are just too different, unless you do your entire app in XHTML (in which case you have problems with IE<9). So you would, I think, have to use either strings (in XML encoded as <response>&lt;div class=... or in a JSON response).

@bobince 2011-10-01 09:11:28

If you don't like using innerHTML then the answer is not to generate the markup at the server side but instead pass back the simple data (in XML as something like <response><id>1</id><color>red</color></response> or JSON for compactness), and then use DOM methods to create the necessary divs and tables.

@Leo Selig 2011-10-01 09:28:46

Okay, thanks a lot! It seems like there is no real alternative to innerHTML so I think I will use it. @bobince I used a method like this also when processing AJAX requests, but in this case the idea is to post load template files via AJAX so this doesn't work, but nevertheless thank you!

@Dr.Molle 2011-09-30 17:57:02

Please describe what you are doing with the returned results. There is a significant difference between a nodeList and a node, nodeLists are LIVE.

So if you assign a nodeList returned by getElementsByClassName() (or similar) to a variable, this variable will change when you remove the nodes inside the nodeList from the DOM.

@Leo Selig 2011-09-30 18:46:29

i have a function like this: handleTmpl = function(tmplNode) { element = parentEl.appendChild($t("div", 0, tmplNode)); var bgPixels = element.getElementsByClassName("gbSelector")[0]; } where tmplNode is the node received by processing the response now element.getElementsByClassName("gbSelector")[0] returns undefined although the development tools clearly show the complete tree in the code

@Dr.Molle 2011-10-01 01:08:19

That's confusing now, what node do you like to access, .gbSelector or .colorSelector? However, see once more the answer by Ӫ_._Ӫ . element will be #0-0 inside your function(appendChild returns the element that has been appended), so element.getElementsByClassName("colorSelector") will not return anything, because .colorSelector is not a child of element, it's element itself.

@user113716 2011-09-30 17:16:01

Since you said that your getElementById("0-0") is successful, then clearly you don't actually have the nodes commented out.

I'm guessing you're doing:


...which will not work because the element selected by ID does not have any descendants with that class.

Since you show HTML comments in the markup, I'd also wonder if you have some different element on the page with the ID "0-0". Take a look for that.

If your nodes are actually commented out, you'll need to first select the comment, and replace it with the markup contained inside:

var container = document.getElementById('test1'),
    comment = container.firstChild;

while( comment && comment.nodeType !== 8 ) {
    comment = comment.nextSibling;

if( comment ) {
    container.innerHTML = comment.nodeValue;

...resulting in:

<div class="testA" id="test1">
    <div class="colorSelector" id="0-0">
        <div class="gbSelector" id="1-0">
            <table style="none" id="2-0"></table>

...but there again, this doesn't seem likely since your getElementsById does work.

@Leo Selig 2011-09-30 18:51:39

see my edition regarding the commenting (sorry) no I definately have no element using also this ID.

@Blender 2011-09-30 17:00:22

<!--<div class="colorSelector" id="0-0">
        <div class="gbSelector" id="1-0">
            <table style="none" id="2-0"></table>

The above code is gray for a reason: it's a comment. Comments aren't parsed by the browser at all and have no influence on the page whatsoever.

You'll have to parse the HTML, read the comments, and make a new DOM object with the contents of the comment.

@user113716 2011-09-30 17:48:17

"using getElementById("0-0") I get the expected result."

@Daniel A. White 2011-09-30 16:59:34

colorSelector is commented out. JavaScript only works within the DOM, and commented out portions aren't in the DOM.

@user113716 2011-09-30 17:42:51

"using getElementById("0-0") I get the expected result."

@user1385191 2011-09-30 18:56:04

Comment nodes are most certainly in the DOM. However, they're treated as CDATA.

@Lightness Races in Orbit 2011-09-30 20:22:57

Doesn't look very commented-out to me.

Related Questions

Sponsored Content

15 Answered Questions

16 Answered Questions

[SOLVED] Ajax request returns 200 OK, but an error event is fired instead of success

39 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

34 Answered Questions

[SOLVED] How can I upload files asynchronously?

15 Answered Questions

13 Answered Questions

[SOLVED] event.preventDefault() vs. return false

9 Answered Questions

[SOLVED] Why does ++[[]][+[]]+[+[]] return the string "10"?

  • 2011-08-26 08:46:14
  • JohnJohnGa
  • 203112 View
  • 1671 Score
  • 9 Answer
  • Tags:   javascript syntax

30 Answered Questions

[SOLVED] How to append something to an array?

3 Answered Questions

[SOLVED] getElementsByTagName of all siblings

Sponsored Content