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)
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)
- 2 Have you tried what you want to try to see if it works? – D4V1D Commented Sep 10, 2015 at 8:15
-
1
$(document.body)[0].appendChild(x);
, here$(document.body)[0]
returns dom object – Pranav C Balan Commented Sep 10, 2015 at 8:16 - 2 If you're going to use native Javascript functions, why would you then use jQuery at all? You're then including thousands of lines of code for absolutely no purpose. – Chrillewoodz Commented Sep 10, 2015 at 8:17
- @Arjun Why do you want to wrap it in jq object? Actually, i don't see any reason from your posted example – A. Wolff Commented Sep 10, 2015 at 8:19
- @D4V1D It certainly does not work. I wanted to know how to make it work. I have also edited the question to highlight my intention. – Arjun Commented Jul 1, 2017 at 9:09
4 Answers
Reset to default 7jQuery 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.
.get()
should do the work like so :
$(document.body).get(0)
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);
this is a native DOM code which should definitely work:
document.body.appendChild(x)