I know I can wrap it's .html() in a tag, but the element itself has a dynamically set id, class, etc. How do I get jQuery to return the element's markup including itself?
The jQuery after() method inserts content AFTER the selected HTML elements. The jQuery before() method inserts content BEFORE the selected HTML elements.
jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed).
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
Three simple, but useful, jQuery methods for DOM manipulation are: text() - Sets or returns the text content of selected elements. html() - Sets or returns the content of selected elements (including HTML markup) val() - Sets or returns the value of form fields.
This will work well:
jQuery.fn.outer = function() {
return $($('<div></div>').html(this.clone())).html();
}
As far as I know, there is no "outerHTML" support directly in jQuery, but you can write a function to emulate it (in browsers other than IE), or use this plugin:
// this will return the element and it's mark-up, of an element
// with the id myTag
var outer = $('#myTag').outerHTML();
Obviously Brandon's is not the only implementation.. I'm sure you could also come up with other clever implementations..
EDIT
If you're keen on avoiding the calls to append, maybe you could try something like this..
function getOuterHTML(el)
{
var wrapper = '';
if(el)
{
var inner = el.innerHTML;
var wrapper = '<' + el.tagName;
for( var i = 0; i < el.attributes.length; i++ )
{
wrapper += ' ' + el.attributes[i].nodeName + '="';
wrapper += el.attributes[i].nodeValue + '"';
}
wrapper += '>' + inner + '</' + el.tagName + '>';
}
return wrapper;
}
// now, to replicate the sample above
var outer = getOuterHTML($('#myTag'));
The only thing is, I'm not sure if all browsers support the attributes array.. but I know the mozilla-family ones do, and IE has native support for outerHTML.. give it a try (for the ones that don't support the attributes array you could use the previous method that uses appends)
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