Can’t access DOM elements created by `createDocumentFragment`

235 Views Asked by At

In my tutorial project, I fill the page with elements created using DocumentFragment. Everything happens as it should: the elements are created, drawn on the page, and displayed in the DOM. The problem is that when I try to access these elements for further work through querySelectorAll, I get an empty array. Why is this happening?

Using the tag <template>, I create and place elements in the right place for me:

var renderPicture = function(photo) {
    var pictureElement = pictureTemplate.cloneNode(true);

    pictureElement.querySelector('.picture__img').src = photo.url;
    pictureElement.querySelector('.picture__stat--comments').textContent = photo.comments.length;
    pictureElement.querySelector('.picture__stat--likes').textContent = photo.likes;

    return pictureElement;
};
var fragment = document.createDocumentFragment();

for (var i = 0; i < photo.length; i++) {
    fragment.appendChild(renderPicture(photo[i]));
}

picturesList.appendChild(fragment);

I refer to the created elements for further interaction:

var pictureImg = document.querySelectorAll('.picture__img');
var pictureImg = document.querySelectorAll('.picture__link');

The browser ignores the elements (even though they are present in the DOM), and returns either an empty collection (with querySelectorAll) or null (if I use querySelector):

NodeList []
length
: 
0
[[Prototype]]
: 
NodeList

What is the problem?

1

There are 1 best solutions below

1
morganney On

You need to access the DocumentFragment of the <template> before using querySelector. The fragment of a template is in the content property.

If you change this line to use the content property it should fix your issue.

pictureTemplate.content.cloneNode(true);