Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Raw HTML of Node in JQuery

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?

like image 788
Lance Avatar asked May 06 '10 08:05

Lance


People also ask

How do I get HTML using jQuery?

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.

What does HTML() do?

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.

What is .html in jQuery?

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.

Is it possible to access the underlying DOM element using jQuery?

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.


1 Answers

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;
like image 70
Dem Pilafian Avatar answered Oct 21 '22 21:10

Dem Pilafian