9

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">
DA.
  • 39,848
  • 49
  • 150
  • 213
P.Henderson
  • 1,001
  • 2
  • 13
  • 23

8 Answers8

11

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();
Rune FS
  • 21,497
  • 7
  • 62
  • 96
5

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();
}
Ram
  • 143,282
  • 16
  • 168
  • 197
2

Using plain old JavaScript simple string manipulation. Find the first closing angle bracket, then take everything up to that point.

function getElementStartTag(element) {
    var html = element.outerHTML;
    var index = html.indexOf(">");
    var startTag = html.substring(0, index + 1);
    return startTag;
}

Example

function getElementStartTag(element) {
  var html = element.outerHTML;
  var index = html.indexOf(">");
  var startTag = html.substring(0, index + 1);
  return startTag;
}

var element = document.getElementById("testSubject");
var startTag = getElementStartTag(element);

alert(startTag); 

// output: <p id="testSubject">
<p id="testSubject">
  <strong>Ignore</strong> this content.
</p>

For JS Fiddle: https://jsfiddle.net/luisperezphd/owj7w1hu/

Luis Perez
  • 27,650
  • 10
  • 79
  • 80
1

You can do it like this: Example

First, you get the containing element and then you get the html text of this element. Then, you split the text by > and you got the text you wanted.

This will work only if there are no elements inside the containing element before your page div. To solve this, you can wrap the page div with a simple element(div?) and it will work.

JQuery:

$(function(){
    var elem = $("#page").parent().html();
    var arr = elem.split('>');
    $("#result").text(arr[0] + " >");
});

HTML:

<div id="cont">
    <div id="page" class="someclass"> more divs </div>
</div>
<br />

Result: <br />
<div id="result">
</div>
Itay Gal
  • 10,706
  • 6
  • 36
  • 75
0

See here: How do you convert a jQuery object into a string?

You need to take your element, clone it, put it into a DIV, and then grab the HTML of said div.

alert( $('<div>').append($('#page').clone()).remove().html() )

If you don't want any child elements or content, then wipe out the contents first after you clone it:

alert( $('<div>').append($('#page').clone().html('')).remove().html() )
Community
  • 1
  • 1
DA.
  • 39,848
  • 49
  • 150
  • 213
  • Hello, thank you but this too will return the entire DIV (
    more divs
    ), instead of just the
    tag and its attributes.
    – P.Henderson Jan 27 '14 at 18:55
  • @P.Henderson so you don't want the child elements...just this item? – DA. Jan 27 '14 at 18:56
  • Yes, now you're very close. Is there anyway to delete the closing tag as well? – P.Henderson Jan 27 '14 at 18:57
  • @P.Henderson at that point, you'll have to deal with it as a string. Possibly using regular expressions. – DA. Jan 27 '14 at 18:58
  • I would suggest that perhaps you could explain what your end-goal objective is here. There might be a better way to accomplish what you are after if we had a better understanding of what you are doing. – DA. Jan 27 '14 at 19:01
0

Just do this based on @Rune answer:

var outer = $("#page")[0].outerHTML;
var inner = $("#page")[0].innerHTML;
var result = outer.replace(inner,"");
console.log(result)
Johann Echavarria
  • 9,695
  • 4
  • 26
  • 32
0

   

 $.fn.startTag = function () {
      // this would act as backup
      var currInnerHtml = this.html();
      // you will need to have some unique string as inner html in order to split using that as in some cases innerHtml might be empty or might have some common ones that would hinder with proper splitting
      var uniqueString = performance.now();
      this.html(uniqueString);
      const startTag = this[0].outerHTML.split(uniqueString )[0];
      this.html(currInnerHtml);
      return startTag;
    };
Anoop Isaac
  • 932
  • 12
  • 15
-1

If you are saying you don't want it wrapped with jQuery, you can always just use:

var ele = document.getElementById('page');

Alternatively you can keep using jQuery and use:

var ele = $("page").get(0);

$("page") returns an array, .get(0) returns the 1st element of that array

palacealex
  • 94
  • 9