1

I need to parse an entire Html tag into a string which I selected using the "this" keyword in the Html tag.

Example:

<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>

when we check the first console, the result will be:

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

In the second console, the result will be:-

[object HTMLButtonElement],

Is there any way I can parse the tag into string like :

"<button id="3" onClick="print(this)">B3</button>"
Martin
  • 15,542
  • 1
  • 29
  • 46

2 Answers2

1

You can pass the node to a new XMLSerializer() like so:

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

Output:

<button id="3" onclick="print(this)">B3</button>
<button xmlns="http://www.w3.org/1999/xhtml" id="3" onclick="print(this)">B3</button>
0stone0
  • 21,605
  • 3
  • 29
  • 49
1

I'd recommend using the outerHTML attribute of the element, which will return the full HTML for that element as shown below:

function print(element) {
  var s = element.outerHTML;
  console.log(typeof(s));
  console.log(s);

  var t = element;
  console.log(typeof(t));
  console.log(t);
}
<button id="3" onClick="print(this)">B3</button>  

Variable s is set to the outerHTML property which is a string.

Variable t uses the original code you posted that just used element which is an object. I've added typeof so you can see that s is a string as requested.

Martin
  • 15,542
  • 1
  • 29
  • 46