简体   繁体   中英

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>

Use .cloneNode or if you don't want 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/

Replace the innerHTML inside the outerHTML with either nothing, or as I did here, ellipses, "...":

var txt = elem.outerHTML.replace(elem.innerHTML, '...');

After selecting the element ( getElementById("foo") ),

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

this will return a string into var txt

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM