Nevermore Nevermore - 5 months ago 24
HTML Question

Get the html tag from an element without the inner text content

Using Javascript I'm looking to take a DOM element and take just it's tag, class, id, etc (the stuff in brackets), but ignore the actual text content within. Kind of like the opposite of


So I'm hoping to get a div like this:

<p id="foo">Ipsum Lorem</p>

into a string this:

<p id="foo"> </p>


Use .cloneNode or if you don't to use that:

Get the nodename and reduce the elements attributes into a string.

'use strict';

const elem = document.getElementById('foobar');
const nodeName = elem.nodeName.toLowerCase();
const attrs = [...el.attributes].map((a) => {
  if (a.value === '')
  else if (a.value.indexOf('"') > -1)
    return `${}='${a.value}'`;
    return `${}="${a.value}"`;
}).join(' ');
const str = `<${nodeName} ${attrs}></${nodeName}>`;