Search code examples
javascriptjquerydomsizzle

JavaScript Methods on jQuery Selectors


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)


Solution

  • 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.