jQuery也可以返回DOM对象,在这里做个记录加深记忆,主要做如下两个记录
1.jQuery哪些方法返回DOM对象
2.jQuery对象与DOM对象相互转换
1、jQuery哪些方法可以返回DOM对象
- 由于
jQuery对象本身是一个集合,所以我们使用[index]索引取出某一项时,取出的就为DOM对象 ,如$("#div")[0],$("div").eq(1)[0],$("div").get()[1],$("div")[5]等都是获得DOM对象
HTML:
<div id="father">
<div class="children">
children1
</div>
<div class="children">
children2
</div>
<div class="children">
children3
</div>
</div>
jQuery:
var obj = $('#father .children')[0];
console.log(obj)
console.log('DOM :' +(obj instanceof HTMLElement));
console.log('jQuery: ' +(obj instanceof jQuery));
控制台输出:

- 使用方法
get(index)方法时,同理取出的为DOM对象。类似的有eq(index),不过eq(index)返回的是jQuery对象。
//使用get(index)方法:
var obj = $('#father .children').get(0);
console.log(obj)
console.log('DOM :' +(obj instanceof HTMLElement));
console.log('jQuery: ' +(obj instanceof jQuery));

//使用.eq(index)方法
var obj = $('#father .children').eq(0);
console.log(obj)
console.log('DOM :' +(obj instanceof HTMLElement));
console.log('jQuery: ' +(obj instanceof jQuery));

- 使用
jQuery DOM元素方法toArray()以DOM对象数组的形式返回jQuery选择器匹配的元素。
var obj = $('#father .children');
console.log(obj)
var element = obj.toArray();
console.log(element);

var obj = $('#father .children');
var element = obj.toArray()[0];
console.log(element);
console.log('DOM :' +(element instanceof HTMLElement));
console.log('jQuery: ' +(element instanceof jQuery));

2、jQuery对象与DOM对象相互转换
DOM对象转jQuery对象,只需要在DOM对象上加$(...)jQuery对象转DOM对象,利用上述的索引[index], get(index), toArray()
$('#father .children').each(function(index){
console.log(this)
console.log('DOM :' +(this instanceof HTMLElement));
console.log('jQuery: ' +($(this) instanceof jQuery));
})

本文介绍了如何使用jQuery获取DOM对象,包括通过索引、get方法及toArray方法等途径,并探讨了jQuery对象与DOM对象之间的相互转换技巧。
176

被折叠的 条评论
为什么被折叠?



