get opening tag including attributes - outerHTML without innerHTML

回眸只為那壹抹淺笑 提交于 2019-11-30 11:34:08
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').

For future Googlers, there is a way to do this without jQuery:

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

Since outerHTML contains the opening tag followed by a mirror of what innerHTML contains, we can substring the outerHTML from 0 (the beginning of the opening tag) to where the innerHTML begins (end of opening tag), and since innerHTML is a mirror of outerHTML, except for the opening tag, only the opening tag will be left!

This one 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.

sus

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+">".

Unfortunately, @AaronGillion's answer isn't reliable as I said in a 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. Remve types (HTMLElement and number) if you want pure Javascript.

Here's a solution I've used:

const wrap = document.createElement('div')
wrap.appendChild(target.cloneNode(true))
const openingTag = wrap.innerHTML.split('>')[0] + '>'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!