最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Methods on jQuery Selectors - Stack Overflow

programmeradmin1浏览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)

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)

Share Improve this question edited Jul 1, 2017 at 8:50 Arjun asked Sep 10, 2015 at 8:15 ArjunArjun 1,3951 gold badge12 silver badges28 bronze badges 5
  • 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
Add a ment  | 

4 Answers 4

Reset to default 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.

.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)
发布评论

评论列表(0)

  1. 暂无评论