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?
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.
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.
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.
The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.
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
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