jQuery对象与DOM对象

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

这里写图片描述

猜你喜欢

转载自blog.csdn.net/mynewclass/article/details/80292071