How to find an element in a documentFragment with JavaScript?

Sometimes, we want to find an element in a documentFragment with JavaScript.

In this article, we’ll look at how to find an element in a documentFragment with JavaScript.

How to find an element in a documentFragment with JavaScript?

To find an element in a documentFragment with JavaScript, we can use the querySelector method.

For instance, we write:

const df = document.createDocumentFragment();
const div = document.createElement('div');
div.id = 'foo';
df.appendChild(div);
const result = df.querySelector('#foo')
console.log(result)

to create a document fragment with createDocumentFragement.

Then we create a div with createElement.

And then we call df.appendChild with div to append the div as a child of the document fragment.

Next, we call df.querySelector with the select for the div to return the div.

Conclusion

To find an element in a documentFragment with JavaScript, we can use the querySelector method.