get opening tag including attributes - outerHTML without innerHTML

后端 未结 7 1348
花落未央
花落未央 2020-12-10 03:22

I would like to retrieve a certain tag element with its attributes from the DOM. For example, from


  link text
         


        
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 03:24

    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 ``. Correct?
        
        return outerHtml.slice(0, openTagLength);
    }
    

    The code is in typescript. Remve types (HTMLElement and number) if you want javascript.

提交回复
热议问题