For example, there is a string

<div>text parent <span>text span</span></div><div>text 1</div><div>text2</div> 

I need to get an array of 3 elements

 ['<div>text parent <span>text span</span></div>','<div>text 1</div>','<div>text2</div>'] 

    2 answers 2

     var html = new DOMParser().parseFromString( '<div>text parent <span>text span</span></div><div>text 1</div><div>text2</div>', "text/html"); var divs = html.body.querySelectorAll('div'); var tags = []; for(let i = 0; i < divs.length; i++){ tags.push(divs[i].outerHTML); } alert(JSON.stringify(tags)); 

    • it works for elements, not for the line - Grundy
    • I don't have a tree house. it is necessary to break the line. - Heisenberg
    • Changed the answer)) - yarkov_aleksei
    • that's it. Thank you very much. - Heisenberg

    Since this is not an AST, but a one-dimensional array, it is not possible to process nested tags.
    Then something like this:

     let str = '<div>text parent <span>text span</span></div><div>text 1</div><div>text2</div>'; function parse(str){ let offset = 0, result = []; // Ищем очередной <div> while((offset = str.indexOf('<div>', offset)) !== -1){ let closed; // Ищем ближайщий закрывающий тэг // Если его нет - кидаем ошибку if ((closed = str.indexOf('</div>', offset)) === -1) throw new Error('Unclosed tag!'); closed += 6; // Вырезаем часть с результатом result.push(str.substring(offset, closed)); // Меняем отступ для нового поиска offset = closed; } return result; } console.info(parse(str)); 

    • This if external only divas will be - Grundy
    • In the question the array is said, an object is needed for a full parse in the tree. I, by the way, at first recursively constructing AST sketched. Then he rolled back to the array, where the nested tags can not be pushed. - user207618 pm
    • I don't see the connection with my comment, if he suddenly has a line at the input in which the container will not only be div — this code will break - Grundy
    • @Grundy, error checking, upgrading and finishing the buns - this is already yourself, this is not freelancing. - user207618
    • thanks for the help. Your answer is excellent. but the one that suits me better. - Heisenberg