get opening tag including attributes - outerHTML without innerHTML

Here is my solution:

opentag=elem.outerHTML.slice(0, elem.outerHTML.length-elem.innerHTML.length-elem.tagName.length-3);

I suppose, that close tag is of the form: "</"+elem.tagName+">".


var wrapper = $('.class').clone().attr('id','').empty();
  • You might want to change the selector to more exactly match the <a> element you're looking for.
  • clone() creates a new copy of the matched element(s), optionally copying event handlers too.
  • I used attr to clear the element's ID so that we don't duplicate IDs.
  • empty() removes all child nodes (the 'innerHTML').

There is a way to do this without jQuery. This also works with <br> tags, <meta> tags, and other empty tags:

tag = elem.innerHTML ? elem.outerHTML.slice(0,elem.outerHTML.indexOf(elem.innerHTML)) : elem.outerHTML;

Because innerHTML would be empty in self-closing tags, and indexOf('') always returns 0, the above modification checks for the presence of innerHTML first.


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 <self-closing tags />:

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. Remove types (HTMLElement and number) if you want JavaScript.