maxhallinan
maxhallinan

Reputation: 1339

appendTo() and append() works, appendChild() does not

As part of a drag-and-drop file upload interface, showImage is called when a file is dropped on the target container. showImage checks that the file is an image, reads the file, creates a new Image object, sets the dropped image file's data as the src, and inserts the new element into the DOM.

For DOM insertion, calling jQuery's appendTo or append works, but the native method appendChild returns the error: Uncaught TypeError: undefined is not a function. What is the reason for this?

var showImage = function(droppedImg) {
    var imageType = /image.*/;

    if (droppedImg.type.match(imageType)) {
        var reader = new FileReader();
        reader.onload = function(e) {
            if (e.target.readyState == FileReader.DONE) {
                newImg = new Image();
                newImg.onload = function(e) {
                    if (e.target.readyState == Image.DONE) {

                        //No DOM insertion. Throws this error: Uncaught TypeError: undefined is not a function
                        var dropTarg = document.querySelectorAll('.drop-container');
                        dropTarg.appendChild(newImg); 


                        //Image inserted into DOM
                        $('.drop-container').append(newImg); 
                        //Image inserted into DOM
                        $(newImg).appendTo('.drop-container'); 

                    }
                };
                newImg.src = reader.result;
            }
        }
        reader.readAsDataURL(droppedImg);
    }
};

Upvotes: 0

Views: 1628

Answers (2)

ProllyGeek
ProllyGeek

Reputation: 15866

querySelectorAll()

always returns live Node List which is array-like , so you have to use either .each() or a for loop , or specify the index of the element you are targetting.

Upvotes: 1

Jason P
Jason P

Reputation: 27022

querySelectorAll() returns a node list. To get the first element, access it by index:

var dropTarg = document.querySelectorAll('.drop-container')[0];
dropTarg.appendChild(newImg);

Some error handling to make sure it found something would probably be in order.

Upvotes: 3

Related Questions