1

I have a function that takes the return value of document.createElement and puts it in a popup on the screen. However, I want this object to be passed to the popup to be an already created div so that I can manipulate the popup content easily.

Basically, I want to turn this:

var magicDiv = document.createElement('div');

Into:

var magicDiv = $('#divToBeTurnedIntoElement').html();

In the first case, document.createElement has a specific return object. I am looking for the jQuery function that returns the same kind of object as document.createElement. In both cases, magicDiv should be the exact same object, but with the jQuery version, it is created based on an existing div. How can I accomplish this?

apsillers
  • 112,806
  • 17
  • 235
  • 239
yesman
  • 7,165
  • 15
  • 52
  • 117
  • 1
    Are you looking for `$('#divToBeTurnedIntoElement')[0]` or [`.get(0)`](https://api.jquery.com/get/)? – apsillers Oct 03 '14 at 12:24
  • `var magicDiv = $("
    ");` is equivalent
    – TCHdvlp Oct 03 '14 at 12:27
  • Do you want `var magicDiv = $($('#divToBeTurnedIntoElement').prop('outerHTML'));` or the clearner way `var magicDiv = $('#divToBeTurnedIntoElement').clone();` – Karl-André Gagnon Oct 03 '14 at 12:28
  • Are you trying to create a new div as a copy of the existing one on the page, or grab a JQuery object referring to the existing div on the page? – HeatherEMSL Oct 03 '14 at 12:28
  • very closely related: [jQuery object and DOM element](http://stackoverflow.com/questions/6974582/jquery-object-and-dom-element) (although that question seems to assume some familiarity with DOM objects) – apsillers Oct 03 '14 at 13:00

1 Answers1

2

I think what you're looking for is a DOM object. DOM objects are often returned by DOM selection and creation methods, like document.createElement and document.getElementById.

A jQuery object contains a list (or, really, is a list) of DOM objects. jQuery saves you the trouble of interacting directly with DOM objects (which have an inconsistently-implemented API across browsers) by exposing a standardized API on the jQuery object.

In order to extract a low-level DOM object out of a jQuery instance, you can use .get(n) to get the nth DOM element from the jQuery object's list of DOM elements:

var magicDiv = $('#divToBeTurnedIntoElement').get(0);

You can also use normal array indexing,$('#divToBeTurnedIntoElement')[0], which is a bit shorter but slightly less flexible (e.g., it doesn't support negative indexing).

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • Thanks, this answer came closest. I used $('#divToBeTurnedIntoElement'.find("#innerDiv"))[0]. This worked great! – yesman Oct 03 '14 at 12:44