1

lets say I have a

<div id="god">
Supertext
</div>

I want to assign

<div id="god">
Supertext
</div>

to a variable

.text()
.html()

only gets "supertext" as a value.

$("#god")
$("#god").clone

returns an object

I don't want to wrap the object and get it's html, because it's time consuming. How can I select the whole item and assign it to a variable in javascript?

Uğur Gümüşhan
  • 2,455
  • 4
  • 34
  • 62
  • Does this help? http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html – Mattie Mar 31 '12 at 23:25

2 Answers2

2

For the browsers that support it you can use the outerHTML

$("#god")[0].outerHTML;
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Why did you use jQuery for? if you use only native javascript functions, don't use jQuery. – gdoron Mar 31 '12 at 23:32
  • because the OP used it, and wanted to answer the specific part only.. But you are right.. for the situation in the example code, it doesn't really offer much help. – Gabriele Petrioli Mar 31 '12 at 23:33
  • 1
    Upvoting because support is important. Did Firefox really only pick up on this in 11? – Mattie Apr 01 '12 at 12:08
  • @zigg, looks that way.. i doubt they would have wrong info on their own website (*but yes.. quite delayed support..*).. – Gabriele Petrioli Apr 01 '12 at 13:20
  • can you edit your answer and explain what [0] indexer stands for? – Uğur Gümüşhan Apr 02 '12 at 14:19
  • @UğurGümüşhan, it is the same as doing [`.get(0)`](http://api.jquery.com/get/). It returns the actual DOM element, instead of a jQuery object. This way we can access the DOM properties like outerHTML. – Gabriele Petrioli Apr 02 '12 at 15:11
0

Don't use jQuery selectors, just to use native javascript functions!

document.getElementById('#god').outerHTML
gdoron
  • 147,333
  • 58
  • 291
  • 367