get opening tag including attributes - outerHTML without innerHTML

后端 未结 7 1343
花落未央
花落未央 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:29

    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
    tags, 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.

提交回复
热议问题