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));
})