Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get entire opening tag using jQuery

Tags:

jquery

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">
like image 649
P.Henderson Avatar asked Jan 27 '14 18:01

P.Henderson


2 Answers

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();
like image 73
Rune FS Avatar answered Oct 17 '22 17:10

Rune FS


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();
}
like image 33
undefined Avatar answered Oct 17 '22 18:10

undefined