19

Say I have

$(":input[type=text]:first")

How do I get

<input type="text" value="" size="28" maxlength="140" tabindex="1" placeholder="search" class="textbox" name="q" autocomplete="off">

Assuming I run this on SO?

Update I don't want to call .parent() since I have lots of other stuff in the parent element.

bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • 1
    Just a note: you really should quote your attribute selectors. `$(":input[type='text']:first")`. – gen_Eric Nov 14 '11 at 19:46
  • Yeah it was merely an example, that's not the actual selector. I usually try and avoid using attribute selectors anyways. – bevacqua Nov 14 '11 at 19:47
  • 1
    possible duplicate of [Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html) – Blazemonger Nov 14 '11 at 19:50
  • @Rocket There's no difference using quotes in the attribute selector. – MacMac Nov 14 '11 at 19:58
  • @lolwut: From the [jQuery docs](http://api.jquery.com/category/selectors/attribute-selectors/): "Attribute values in selector expressions **must** be surrounded by quotation marks." – gen_Eric Nov 14 '11 at 20:04

5 Answers5

51

How about

$(selector).prop("outerHTML");
William
  • 8,007
  • 5
  • 39
  • 43
23

An old trick:

var selector = ":input[type=text]:first";

var str = $(selector).clone().wrap('<div/>').parent().html();

Update You don't need to worry about calling .parent() since you're working with an orphaned clone of the original selector.

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
5

Use jQuery.html() by appending to a created element.

$('<div/>').append($(":input[type=text]:first").clone()).html()

Here is a fiddle providing an example: http://jsfiddle.net/Zwbmx/1/

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
0

Following on what @Blazemonger have answered, if you are going to send this html content to the server, it's worth to get rid of all unnecessary tags, white-spaces and line-breaks that don't add any value.

var quote = $(".invoice") //get hidden print-version DOM element
    .clone()
    .wrap('<div/>')
    .parent()
    .html()
    .replace(/    /g, '') //get rid of indentation spaces
    .replace(/(\r\n|\n|\r)/gm, "") //get rid of line breaks
    .replace(/<!--[\s\S]*?-->/g, ""); //get rid of comment tags

My html had 50kb, after getting rid of this stuff, it got reduced to 4kb!

ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44
-1

How about:

var str = $(selector)[0]

Maybe add a check that there is one element returned.

Tarion
  • 16,283
  • 13
  • 71
  • 107