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">
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();
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With