HTML Rewriter respond with JSON constructed of all elements

I use the HTMLRewriter is there any way to return a custom response (json) from the handleRequest function? I assume the HTMLRewriter loops over all elements so what I want is to build out my json of specific data I get from the elements and send it back as response (json).

addEventListener('fetch', event => {
// respond with json constructed in the element method