Javascript 确定UL内是否有1个或多个LI
如何使用JavaScript确定UL中是否包含1个或多个LI 伪码Javascript 确定UL内是否有1个或多个LI,javascript,jquery,Javascript,Jquery,如何使用JavaScript确定UL中是否包含1个或多个LI 伪码 if('ul#items' has >= 1 LI){ 谢谢,使用jQuery: if ($('ul#items').children('li').length) { // etc. } if( $('#items li').length >= 1 ){... $('ul#items li').length >= 1 您可以使用: $('ul#items li').length 使用jQuer
if('ul#items' has >= 1 LI){
谢谢,使用jQuery:
if ($('ul#items').children('li').length) {
// etc.
}
if( $('#items li').length >= 1 ){...
$('ul#items li').length >= 1
您可以使用:
$('ul#items li').length
使用jQuery:
if( $('#items li').length >= 1 ){...
$('ul#items li').length >= 1
没有jQuery:
document.getElementById('items').getElementsByTagName('li').length >= 1
使用
document.getElementById(“items”).childNodes.length
和数字比较运算符。如果您的ul
确实包含li
以外的其他节点,则必须对其进行筛选
在jQuery中:
$("#items").children("li").length
我想您只需要直接子对象,所以如果使用jQuery,请不要使用find()
if($('ul > li').size()>0) {
}
这将检查UL元素是否有超过0个直接子li元素。UL也可以将文本节点作为子元素,因此
childNodes。长度不是一个好选项。不过,您可以使用getElementsByTagName('li')
。这取决于文档。如果动态添加li
s,则不会有文本节点。但是如果您的列表包含其他列表,getElementsByTagName
也是错误的。或者使用>0
进行简化。
if ($('ul#items > li').length >= 1)