Get entire opening tag using jQuery

jquery

Solution

You could always use the DOM element attribute outerHTML

$(selector)[0].outerHTML

which simply gets the first DOM element of the selection and then acquires the html using the DOM attribute outerHTML

EDIT If you do not want the content but only the enclosing tag you could do this

$.fn.tag = function(){
    return this[0].outerHTML.replace(this.html(),"");
};

or if you only want the start tag

$.fn.startTag = function(){
    return this[0].outerHTML.split(this.html())[0];
};

you can then use it like this to get the enclosing tag

$("#page").tag();

or like this to get the start tag

$("#page").startTag();

Problem

Let's say the HTML is: ``` <div id="page" class="someclass"> more divs </div> ``` How do I get the entire opening tag and its attributes (but not the closing tag) as it shows in the HTML by using the ID? For example: ``` $('#page').tag(); ``` Would then return: ``` <div id="page" class="someclass"> ```

Original source

Related problems