Nevermore Nevermore - 2 months ago 11
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

innerHTML
/
textContent
.

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

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


into a string this:

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

Answer

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 === '')
    return a.name;
  else if (a.value.indexOf('"') > -1)
    return `${a.name}='${a.value}'`;
  else
    return `${a.name}="${a.value}"`;
}).join(' ');
const str = `<${nodeName} ${attrs}></${nodeName}>`;

https://jsfiddle.net/k22tyqbr/3/