0

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)

Arjun
  • 1,261
  • 1
  • 11
  • 26
  • 2
    [Have you tried](http://meta.stackoverflow.com/questions/289336/is-it-okay-to-downvote-questions-asking-if-some-code-could-work-but-not-actually) what you want to try to see if it works? – D4V1D Sep 10 '15 at 08:15
  • 1
    `$(document.body)[0].appendChild(x);`, here `$(document.body)[0]` returns dom object – Pranav C Balan Sep 10 '15 at 08: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 Sep 10 '15 at 08: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 Sep 10 '15 at 08: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 Jul 01 '17 at 09:09

4 Answers4

7

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.
Dennis
  • 14,210
  • 2
  • 34
  • 54
2

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);
kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29
  • @Arjun Can you elaborate on your statement? – kamil-mrzyglod Sep 10 '15 at 08:23
  • @Jai No. `var elem = document.querySelector('#parent .child:nth-child(1)'); $(elem).addClass('HelloWorld');` Calling jQuery methods on Javascript objects – Tushar Sep 10 '15 at 08:30
  • @Jai I know, but that's what the OP wants _vice versa_, I know this is not preffered when you can use jQuery directly but OP wants it – Tushar Sep 10 '15 at 08:38
2

.get() should do the work like so :

$(document.body).get(0)
Norlihazmey Ghazali
  • 9,000
  • 1
  • 23
  • 40
1

this is a native DOM code which should definitely work:

document.body.appendChild(x)
MoLow
  • 3,056
  • 2
  • 21
  • 41