I have used $("#parent").html()
to get the inner html of #parent
, but how do I get the html of the parent itself?
The use case is, I grab an input node like this:
var field = $('input');
I would like to be able to get the raw html of that node (<input type='text'>
) with something like field.html()
, but that returns empty. Is this possible?
To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.
Definition and Usage The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.
The html() Method in jQuery is used to set or return the innerHTML content of the selected element. Syntax: It returns the content of first matched element. $(selector).html() It sets the content of matched element.
The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.
This question is very old, but there is now an easy solution:
const html = $('input').prop('outerHTML');
Example string value of html
:
<input type="input">
Fiddle with it:
https://jsfiddle.net/u0a1zkL1/3
And, the technique mentioned in Optimae's comment also works:
const html = $('input')[0].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