I would like to retrieve a certain tag element with its attributes from the DOM. For example, from
link text
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.