Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected element's outer HTML

Tags:

jquery

I'm trying to get the HTML of a selected object with jQuery. I am aware of the .html() function; the issue is that I need the HTML including the selected object (a table row in this case, where .html() only returns the cells inside the row).

I've searched around and found a few very ‘hackish’ type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of outerHtml functionality?

like image 397
Ryan Avatar asked Mar 10 '10 19:03

Ryan


People also ask

How do you capture an element in HTML?

Users can use getElementById() method to access HTML element using the id. If any element doesn't exist with the passed id into the getElementById method, it returns the null value. Syntax: document.

How do I get the contents of an element in HTML?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

Is there an outerHTML?

The outerHTML is the HTML of an element including the element itself. Contrast this with the innerHTML of the element, which is the HTML contained within an elements opening and closing tags. By definition, elements without both opening and closing tags do not have innerHTML.

What does outerHTML return?

The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.


1 Answers

I believe that currently (5/1/2012), all major browsers support the outerHTML function. It seems to me that this snippet is sufficient. I personally would choose to memorize this:

// Gives you the DOM element without the outside wrapper you want $('.classSelector').html()  // Gives you the outside wrapper as well only for the first element $('.classSelector')[0].outerHTML  // Gives you the outer HTML for all the selected elements var html = ''; $('.classSelector').each(function () {     html += this.outerHTML; });  //Or if you need a one liner for the previous code $('.classSelector').get().map(function(v){return v.outerHTML}).join(''); 

EDIT: Basic support stats for element.outerHTML

  • Firefox (Gecko): 11 ....Released 2012-03-13
  • Chrome: 0.2 ...............Released 2008-09-02
  • Internet Explorer 4.0...Released 1997
  • Opera 7 ......................Released 2003-01-28
  • Safari 1.3 ...................Released 2006-01-12
like image 110
Eric Hu Avatar answered Oct 25 '22 15:10

Eric Hu