简体   繁体   English

如何确定对象是否具有某些元素的子元素?

[英]how determine if object has child of certain element?

I have a very simple function, which I want to work only if selected object has child of certain type - in this case if it has ul nested. 我有一个非常简单的函数,只有在选定对象具有某种类型的子对象的情况下,我才想使用它-在这种情况下,如果它具有ul嵌套。

I have tried with this: 我已经尝试过:

var onMouseOver = function() {
 if (this.getElementsByTagName('ul') > 0);{
   console.log('entered');
 }
}

and this: 和这个:

var onMouseOver = function() {
 if (this.querySelector('ul') != null);{
   console.log('enter');
 }
}

but it doesn't help - function still launches, even when it returnes 'null'. 但这无济于事-即使返回“ null”,功能仍会启动。

You should be looking at the length property of those selectors. 您应该查看这些选择器的length属性。

 var onMouseOver = function() { if (this.querySelectorAll('ul').length > 0);{ console.log('enter'); } } 

or 要么

 var onMouseOver = function() { if (this.getElementsByTagName('ul').length > 0);{ console.log('entered'); } } 

try this one :) 试试这个:)

 function ok(obj) { var l = obj.children.length; for (var i = 0; i <= l; i++) { if (obj.children[i].tagName == "UL") { var c = obj.children[i].children[0]; alert("child id is :-" + c.tagName); alert("child id is :-" + c.id); alert("child value is :-" + c.innerHTML); break; } } } 
 #child { display: none; } 
 <!DOCTYPE html> <html> <body> <div id="Parent" onmouseover="ok(this)">Find Child ? mouse over me <p id="child">I'm Child</p> <ul> <li id="list">hello</li> </ul> </div> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定JSON对象是否具有子项 - How to determine if JSON object has child items 如何用 JavaScript 确定某个元素声明了某个空属性? - How to determine with JavaScript that some element has certain empty attribute declared? javascript:仅在父元素处于活动状态且子元素具有特定类的情况下,才如何向子元素添加属性? - javascript: how to add an attribute to a child element ONLY if a parent element is active AND child element has a certain class? 查找由“ this”表示的具有特定类的元素的子元素 - Find the child of the element represented by “this” that has a certain class jQuery-如果子元素具有某些CSS类,如何将CSS添加到父元素 - jQuery - How to add css to a parent element if child element has certain css class 如何确定HTML元素是否具有伪元素? - How to determine if HTML element has pseudo element? Vanilla JS Selector用于元素的子元素具有特定属性的元素 - Vanilla JS Selector for an element that has a child element with a certain attribute 循环遍历div数组以确定每个元素是否都有一个子元素 - Loop through an array of div's to determine if every element has a child 如何确定子元素是否在包含祖先的元素之外? - How to determine if a child element is outside the containing ancestor? 如何创建一个动态下拉选择元素,其选项计数根据某个 div 的子元素数量而变化? - How to create a dynamic dropdown selection element whose option count changes according to the number to child a certain div has?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM