Get entire opening tag using jQuery
You can define a jQuery method that returns the outerHTML
property.
$.fn.tag = function() {
return this.first().clone().empty().prop('outerHTML');
}
$('#page').tag();
http://jsfiddle.net/w2FAb/
For removing the closing tag:
$.fn.tag = function() {
var r = this[0].nodeName.toLowerCase();
return this.first()
.clone()
.empty()
.prop('outerHTML')
.replace('</'+r+'>', '');
}
For more than one selected element, the following returns an array:
$.fn.tag = function() {
return this.map(function() {
var r = this.nodeName.toLowerCase();
return $(this).clone()
.empty()
.prop('outerHTML')
.replace('</'+r+'>', '');
}).get();
}
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();