简体   繁体   English

如何将html标签保存为数组?

[英]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>

array output阵列输出

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);
  • First we have tags array to store our output首先我们有标签数组来存储我们的输出
  • this.document.body.children gives us all the children of body tag as an nodelist (a bit like an array) of HTMLElementObjects this.document.body.children 为我们提供了 body 标签的所有孩子作为 HTMLElementObjects 的节点列表(有点像一个数组)
  • It also has a property named 'length' where it provides the number of its children.它还有一个名为“length”的属性,用于提供其子节点的数量。 We used it for our loop.我们将它用于我们的循环。
  • Each of these objects have a property named 'outerHTML' (It is same as the innerHTML property but the difference only that it also includes the tags of that element)这些对象中的每一个都有一个名为“outerHTML”的属性(它与 innerHTML 属性相同,但不同之处仅在于它还包含该元素的标签)
  • Now just push all these to our output array.现在只需将所有这些推送到我们的输出数组。
  • DONE!完毕!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM