I would like to retrieve a certain tag element with its attributes from the DOM. For example, from
link text
Unfortunately, @AaronGillion's answer isn't reliable as I said in my comment. Thank @sus. I recommend his/her way with a little change to support :
function getOpenTag(element: HTMLElement): string {
const outerHtml = element.outerHTML;
const len = outerHtml.length;
const openTagLength = outerHtml[len - 2] === '/' ? // Is self-closing tag?
len :
len - element.innerHTML.length - (element.tagName.length + 3);
// As @sus said, (element.tagName.length + 3) is the length of closing tag. It's always `${tagName}>`. Correct?
return outerHtml.slice(0, openTagLength);
}
The code is in typescript. Remve types (HTMLElement and number) if you want javascript.