为什么childElementCount不能与jQuery一起使用?

时间:2014-02-19 15:12:48

标签: javascript jquery

我想将childElementCount与jQuery一起使用,那么有什么方法可以检查这个吗?

以下是工作javascript的代码:

var box = document.getElementById('list_items').childElementCount;

alert(box);

但为什么这不适用于jQuery。

var box = $('list_items').childElementCount;

我在这里找到了stackoverflow帖子:

访问:Jquery ChildElementCount

但它显示:

var count = $(result).find('RESULTS').first().children().length;

也许更愿意然后使用这个代码javascript是好方法,但还有其他DOM属性,我想与jQuery一起使用。

3 个答案:

答案 0 :(得分:3)

您正在jQuery对象上调用DOM属性。您必须获取嵌入在jQuery对象中的DOM元素:

var box = $('#list_items').get(0).childElementCount;

答案 1 :(得分:2)

它是dom元素的属性,您还需要对list_items元素使用id selector

var box = $('#list_items').prop('childElementCount');

$('#list_items')返回一个jQuery object,它没有childElementCount属性,它属于dom元素,所以你需要获取底层dom元素的属性值,你可以使用.prop()要做到这一点

答案 2 :(得分:1)

您需要将#放在ID选择器之前。然后childElementCount是dom元素的属性,因此将jQuery对象转换为dom对象

var box = $('#list_items')[0].childElementCount;

$('#list_items')返回一个jQuery对象,$('#list_items')[0]返回dom对象

相关问题