What I want is outerHTML without innerHTML.
I don't want to compute string of innerHTML, as it might be expensive and I've to do this operation frequently, is there a simple way to get it?
What I want is outerHTML without innerHTML.
I don't want to compute string of innerHTML, as it might be expensive and I've to do this operation frequently, is there a simple way to get it?
You can use the elements' internals and build the string yourself from that:
function getTagHTML(el) {
if (!el instanceof HTMLElement) return null;
let result = `<${el.tagName.toLowerCase()}`;
for (const attribute in el.attributes) {
if (el.attributes[attribute].nodeValue)
result += ` ${el.attributes[attribute].name}="${el.attributes[attribute].nodeValue.replace(/"/g, """)}"`
}
result += `></${el.tagName.toLowerCase()}>`;
return result;
}
console.log(getTagHTML(document.getElementById('outer')));
<div id="outer" class='i-want-"this"'>
<span>I do not want this</span>
</div>
If the opening tag is enough, that's easy:
const tag = `${outer.outerHTML.split('>')[0]}>`;
console.log(tag);
<div id="outer" class="i-want-this">
<span>I do not want this</span>
</div>
Please note, that as pointed out by Quentin, the >
cannot be relied upon to mark the end of the opening tag as it may very well occur within any attribute's value.
As far as I know there is no JavaScript "native" way to get the HTML Tag without its' content. How about using jQuery and
let oElement = $("#myElementsID");
or
let oElement = $(".myElementsClass");
That won't give you the HTML tag, but all the information that you could ask for in a neat object.