var startReg = new RegExp(/^<[^/>]+>/); var selfCloseReg = new RegExp(/^<[^<>/]+/>/); var endReg = new RegExp('^</[^>]+>'); var textNode = new RegExp(/^[^<]+/); function parse(html) { var stack = []; var res; while (html) { var startTag = startReg.exec(html); if (startTag) { res = startTag[0]; stack.push(res); html = html.slice(res.length); continue; } var textTag = textNode.exec(html); if (textTag) { res = textTag[0]; stack.push(res); html = html.slice(res.length); continue; } var endTag = endReg.exec(html); if (endTag) { res = endTag[0]; stack.push(res); html = html.slice(res.length); continue; } var selfCloseTag = selfCloseReg.exec(html); if (selfCloseTag) { res = selfCloseTag[0]; stack.push(res); html = html.slice(res.length); continue; } } return stack; } var template = '<div id="main">name</div><span class="loading"><input type="text" />name</span>'; console.log(parse(template));