답변:
몇 가지 방법 :
if (element.firstChild) {
// It has at least one
}
또는 hasChildNodes()기능 :
if (element.hasChildNodes()) {
// It has at least one
}
또는 length속성 childNodes:
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}
모든 최신 브라우저 (및 IE8-사실, IE6까지)에서 자식 요소 (텍스트 노드, 속성 노드 등과 반대) 에 대해서만 알고 싶다면 다음 과 같이 할 수 있습니다. ( Florian 에게 감사드립니다 !)
if (element.children.length > 0) { // Or just `if (element.children.length)`
// It has at least one element as a child
}
즉,에 의존 children에 정의되지 않은 특성, DOM1 , DOM2 , 또는 DOM3 하지만 거의 보편적 인지지를 받고있다. (그것은에서 크롬, 파이어 폭스, 오페라 IE6과까지 작동 이상 까지 다시이 원래 작성되었습니다 년 11 월 2012 년 한.) 이전의 모바일 기기를 지원하는 경우, 반드시 지원을 확인 할 수 있습니다.
IE8 및 이전 지원이 필요하지 않은 경우 다음을 수행 할 수도 있습니다.
if (element.firstElementChild) {
// It has at least one element as a child
}
그것은 firstElementChild. 마찬가지로 children, DOM1-3에서도 정의되지 않았지만 childrenIE9까지는 IE에 추가되지 않았습니다.
DOM1에 정의 된 것을 고수하려면 (아마도 정말 모호한 브라우저를 지원해야 할 수도 있음) 더 많은 작업을 수행해야합니다.
var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
hasChildElements = true;
break;
}
}
이 모든 것이 DOM1의 일부 이며 거의 보편적으로 지원됩니다.
이것을 함수로 감싸는 것은 쉽습니다. 예 :
function hasChildElement(elm) {
var child, rv;
if (elm.children) {
// Supports `children`
rv = elm.children.length !== 0;
} else {
// The hard way...
rv = false;
for (child = element.firstChild; !rv && child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
rv = true;
}
}
}
return rv;
}
div가진 요소 div가 있는지 어떻게 확인 xyz합니까?
for (child = element.firstChild; child; child = child.nextSibling ), 투표 와 같은 루프 조건을 본 적이 없습니다 . Thanks TJ
element.firstChild아닌 null경우 전적으로 가능합니다 . 순전히 요소 자식 목록입니다 . 최신 브라우저에서는 대신 사용할 수 있습니다 . element.children.length0firstChildchildrenfirstElementChild
요소에 자식 노드가 있는지 확인할 수 있습니다 element.hasChildNodes(). Mozilla에서는 태그 뒤에 공백이 있으면 true를 반환하므로 태그 유형을 확인해야합니다.
다음을 수행 할 수도 있습니다.
if (element.innerHTML.trim() !== '') {
// It has at least one
}
이것은 trim () 메서드를 사용하여 공백 만있는 (이 경우 hasChildNodestrue를 반환) 빈 요소를 비어있는 것으로 처리 합니다.
늦었지만 문서 조각은 노드가 될 수 있습니다.
function hasChild(el){
var child = el && el.firstChild;
while (child) {
if (child.nodeType === 1 || child.nodeType === 11) {
return true;
}
child = child.nextSibling;
}
return false;
}
// or
function hasChild(el){
for (var i = 0; el && el.childNodes[i]; i++) {
if (el.childNodes[i].nodeType === 1 || el.childNodes[i].nodeType === 11) {
return true;
}
}
return false;
}
참조 :
https://github.com/k-gun/so/blob/master/so.dom.js#L42
https://github.com/k-gun/so/blob/master/so.dom.js # L741
childElementCount 속성을 시도하십시오 .
if ( element.childElementCount !== 0 ){
alert('i have children');
} else {
alert('no kids here');
}
재사용 가능한 isEmpty( <selector> )기능.
요소 컬렉션으로 실행할 수도 있습니다 (예제 참조).
const isEmpty = sel =>
![... document.querySelectorAll(sel)].some(el => el.innerHTML.trim() !== "");
console.log(
isEmpty("#one"), // false
isEmpty("#two"), // true
isEmpty(".foo"), // false
isEmpty(".bar") // true
);
<div id="one">
foo
</div>
<div id="two">
</div>
<div class="foo"></div>
<div class="foo"><p>foo</p></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
true하나의 요소가 공백이나 줄 바꿈 옆에 어떤 종류의 내용을 갖 자마자 반환 하고 루프를 종료합니다.
<script type="text/javascript">
function uwtPBSTree_NodeChecked(treeId, nodeId, bChecked)
{
//debugger;
var selectedNode = igtree_getNodeById(nodeId);
var ParentNodes = selectedNode.getChildNodes();
var length = ParentNodes.length;
if (bChecked)
{
/* if (length != 0) {
for (i = 0; i < length; i++) {
ParentNodes[i].setChecked(true);
}
}*/
}
else
{
if (length != 0)
{
for (i = 0; i < length; i++)
{
ParentNodes[i].setChecked(false);
}
}
}
}
</script>
<ignav:UltraWebTree ID="uwtPBSTree" runat="server"..........>
<ClientSideEvents NodeChecked="uwtPBSTree_NodeChecked"></ClientSideEvents>
</ignav:UltraWebTree>
childrenDOM4에만 추가되었다는 것을 몰랐습니다. 알려진 모든 브라우저에서 지원된다는 것을 알기 때문에 거의 DOM0 / 1이라고 생각했습니다.