【问题标题】:How to parse a selected html element into string [duplicate]如何将选定的html元素解析为字符串[重复]
【发布时间】:2021-09-19 19:07:46
【问题描述】:

我需要将整个 Html 标记解析为我在 Html 标记中使用“this”关键字选择的字符串。

例子:

<button id="3" onClick="print(this)">B3</button>  
<script type="text/javascript">
  function print(element)
  {
      console.log(element);
      var x = element.toString()
      console.log(x)
  }
</script>

当我们检查第一个控制台时,结果将是:

<button id="3" onClick="print(this)">B3</button>,

在第二个控制台中,结果将是:-

[object HTMLButtonElement],

有什么办法可以把标签解析成字符串,比如:

"<button id="3" onClick="print(this)">B3</button>"

【问题讨论】:

  • 试试element.outerHTML

标签: javascript html


【解决方案1】:

您可以像这样将节点传递给new XMLSerializer()

function print(element)
{
    console.log(element);
    var x = new XMLSerializer().serializeToString(element);
    console.log(x)
}
&lt;button id="3" onClick="print(this)"&gt;B3&lt;/button&gt;

输出:

<button id="3" onclick="print(this)">B3</button>
<button xmlns="http://www.w3.org/1999/xhtml" id="3" onclick="print(this)">B3</button>

【讨论】:

    【解决方案2】:

    我建议使用元素的outerHTML 属性,它将返回该元素的完整 HTML,如下所示:

    function print(element) {
      var s = element.outerHTML;
      console.log(typeof(s));
      console.log(s);
    
      var t = element;
      console.log(typeof(t));
      console.log(t);
    }
    &lt;button id="3" onClick="print(this)"&gt;B3&lt;/button&gt;  

    变量s 设置为outerHTML 属性,即string

    变量t 使用您发布的原始代码,该代码刚刚使用element,它是一个对象。我已经添加了typeof,因此您可以看到s 是一个string 所要求的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      相关资源
      最近更新 更多