Reputation: 1365
How do I access the core HTML DOM element from a JQuery Selector?
For example, the following code:
$(document.body).appendChild(x);
will not work because the DOM object that $(document.body)
is referring to is wrapped around by a JQuery Selector Object.
(Please don't suggest that I can use jQuery's append()
instead, it's just for an example)
Upvotes: 0
Views: 943
Reputation: 14495
jQuery Objects are arrays of native DOM elements. So try this:
$(document.body)[0].appendChild(x)
On the other hand, if you have a native DOM element, you can just wrap it in a jQuery Object to use jQuery's methods on it.
var x = document.getElementsByTagName('div');
$(x).remove(); // wrap it with $ to use jQuery methods.
Upvotes: 7
Reputation: 5008
Since jQuery is built on top of Sizzle you can refer to the Sizzle's documentation under this link.
Since $
is just an alias, you can refer to the documentation:
$(String selector[, DOMNode context[, Array results]])
The main function for finding elements. Uses querySelectorAll if available.
the above will return an array, even if there is only one element. So if you want to refer to the one element exactly, you have to use array index like:
$(document.body)[0].appendChild(x);
Upvotes: 2
Reputation: 9060
.get()
should do the work like so :
$(document.body).get(0)
Upvotes: 2
Reputation: 3084
this is a native DOM code which should definitely work:
document.body.appendChild(x)
Upvotes: 1