2016-03-07 179 views
2

如果給定元素只有一個子元素(包括文本節點,但忽略空格),如何使用jQuery或JavaScript進行測試。檢查元素是否只有一個子元素

示例:對於標記元素「DIV」以下時,測試將失敗,因爲它有兩個子元素:p和文本節點:

<div> 
    <p>Test-1</p> - subline 
</div> 

示例:對於以下標記元素「DIV」,測試應該通過,因爲它只有一個子元素:p(儘管空格被忽略):

<div> 
    <p>Test-1</p> 
</div> 

好像element.children()將無法工作,因爲它忽略了文本節點。 element.contents()可能有效,但不會忽略空格。

回答

3

你將不得不使用自定義過濾器

var elements = $('div'); 
 

 
elements.each(function() { 
 
    var element = $(this); 
 
    var count = element.contents().filter(function() { 
 
    return this.nodeType == Node.ELEMENT_NODE || (this.nodeType == Node.TEXT_NODE && !!$.trim(this.nodeValue)) 
 
    }).length; 
 

 
    snippet.log(this.id + ': ' + count) 
 
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="1"> 
 
    <p>Test-1</p> 
 
</div> 
 
<div id="2"> 
 
    <p>Test-1</p>1 
 
</div> 
 
<div id="3"> 
 
    <p>Test-1</p><span>x</span> 
 
</div> 
 
<div id="4"> 
 
    2 
 
    <p>Test-1</p>3 
 
</div>

+0

任何方式重構並使其更小。 – Nick

+1

@尼克爲什麼會這麼重要?如果您需要反覆使用它,請將其解壓縮到一個函數中。 –

+0

@RoryMcCrossan它的工作原理,但簡潔一些將是可取的。我嘗試重構它:element.contents()。filter(':only-child')。length。如果沒有比Arun的答案更好或更短的方法,那麼我會很樂意接受它。 – Nick

1

你可以嘗試簡單的JS作爲

element[0].childNodes.length 

這將包括文本節點以及正常的子節點。

如果一個給定的元素只有一個子元素(包括文本節點, 但忽略空格)。

要排除的空格

element.contents().filter(function() { 
    return this.nodeType === 3 && this.nodeValue.trim().length > 0; 
}).length; //to get the number of text nodes which are not white-spaces 

或純JS

element[0].childNodes.filter(function() { 
    return this.nodeType === 3 && this.nodeValue.trim().length > 0; 
}).length; 
+2

將不排除空格 –

+0

@ArunPJohny所做的更改,但你已經做到了我想 – gurvinder372

0

非jQuery版本。

可以優化,但這個工作。 value.nodeType === 1來檢查它是否是一個元素,我們增加計數器。

var count = 0; 
Array.prototype.slice.call(document.getElementById('parent_id_here').childNodes, 0).forEach(function (value) { 
    if (value.nodeType === 1) { 
     count++; 
    } 
}); 

Demo

0

您可以使用此條件:

$('div').html().trim() == $('div > *:first-child')[0].outerHTML.trim() 
相關問題