1

I need to serialize 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.log statement, the result will be:

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

In the second console.log statement, the result will be:

[object HTMLButtonElement]

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

"<button id="3" onClick="print(this)">B3</button>"
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

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
  • 34,288
  • 4
  • 39
  • 64
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
  • 16,093
  • 1
  • 29
  • 48