【问题标题】:How to save html tags as array?如何将html标签保存为数组?
【发布时间】:2020-05-24 06:14:53
【问题描述】:

我想将所有 HTML 标签保存到数组中,例如:

Var a = '<p> hi</p> <h2>hello</h2>'

结果如下:

result = [
  0:"<p> hi</p>"
  1:"<h2>hello</h2>"
]

【问题讨论】:

  • 只要做一个数组,循环遍历页面中的所有元素,然后推入数组
  • 检查这个stackoverflow question关于序列化html

标签: javascript html vuejs2


【解决方案1】:

我得到了解决方案,但它不是 100% 完美的。检查这段代码,我已经提取了 id 为“demo”的 div 元素的子 html 元素。您可以过滤输出数组以删除未定义并拆分包含两个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

【讨论】:

    【解决方案2】:

    在您的示例中,您可以使用:

    /
      <   // Match literal <
      >    // Match literal <
      .*?  // Match any character zero or more times, non greedy
      <\/ // Match literal </
      >    // Match literal >
    /g
    

    你的例子:

        var str = '<p> hi</p> <h2>hello</h2>'
        const arr = str.match(/<.*?>.*?<\/.*?>/g); // ["<p> hi</p>","<h2>hello</h2>"]
        console.log(arr);

    但我不建议使用正则表达式解析 HTML。

    查看更多:RegEx match open tags except XHTML self-contained tags

    【讨论】:

      【解决方案3】:

      这是我找到的最简单的方法。我希望它会帮助别人!

      var tags = [];
      
       var alltagsObjects = this.document.body.children;
      
      for(i=0; i < alltags.length; i++){ 
      
        tags.push(alltags[i].outerHTML);
      
      }
      
        console.log(tags);
      
      • 首先我们有标签数组来存储我们的输出
      • this.document.body.children 将 body 标记的所有子代作为 HTMLElementObjects 的节点列表(有点像数组)提供给我们
      • 它还有一个名为“length”的属性,用于提供其子代的数量。我们将它用于我们的循环。
      • 这些对象中的每一个都有一个名为“outerHTML”的属性(它与 innerHTML 属性相同,但不同之处在于它还包括该元素的标签)
      • 现在只需将所有这些推送到我们的输出数组。
      • 完成!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-17
        • 2013-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多