[英]How to save html tags as array?
I want to save my all HTML tags to array like:我想将所有 HTML 标签保存到数组中,例如:
Var a = '<p> hi</p> <h2>hello</h2>'
Result like :结果如:
result = [
0:"<p> hi</p>"
1:"<h2>hello</h2>"
]
I got the solution but it is not 100% perfect.我得到了解决方案,但它不是 100% 完美的。 Check this code, I have extracted the child html elements of the div element with id "demo".
检查此代码,我已经提取了 id 为“demo”的 div 元素的子 html 元素。 You can filter the output array for removing the undefined and split the array element that containing two html elements.
您可以过滤输出数组以删除 undefined 并拆分包含两个 html 元素的数组元素。
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Testing Web</title> </head> <body> <div id="demo"> <h1>I am here</h1> <p>I am a paragraph</p> <div class="div"> <h3>I am h3 tag</h3> </div> </div> </body> <script> var arr = []; var x = document.querySelector("#demo").childNodes; x.forEach(element => { arr.push(element.outerHTML); }); console.log(arr); </script> </html>
In your example you can use:在您的示例中,您可以使用:
/
< // Match literal <
> // Match literal <
.*? // Match any character zero or more times, non greedy
<\/ // Match literal </
> // Match literal >
/g
Your example :你的例子:
var str = '<p> hi</p> <h2>hello</h2>' const arr = str.match(/<.*?>.*?<\\/.*?>/g); // ["<p> hi</p>","<h2>hello</h2>"] console.log(arr);
however I do not recommend to parse HTML with regex.但是我不建议使用正则表达式解析 HTML。
see more: RegEx match open tags except XHTML self-contained tags查看更多:正则表达式匹配除 XHTML 自包含标签之外的开放标签
Here is the most simple and easy method I found for this.这是我为此找到的最简单易行的方法。 I hope it will help someone!
我希望它会帮助某人!
var tags = [];
var alltagsObjects = this.document.body.children;
for(i=0; i < alltags.length; i++){
tags.push(alltags[i].outerHTML);
}
console.log(tags);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.